You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor WASM表单提交验证逻辑的可重用组件封装问询

Absolutely! You can wrap that account validation logic into a reusable component/service without overhauling your existing data annotation-based code. Here's a straightforward, maintainable approach:

Step 1: Create a Reusable Account Validation Service

First, extract the validation logic into a dedicated service class. This keeps your form code clean and lets you reuse the rules anywhere else in your app:

public class AccountValidationService
{
    // Returns a dictionary of errors (matches the format your validator expects)
    public Dictionary<string, List<string>> ValidateAccount(int provisionAccountTypeId, string accountValue)
    {
        var errors = new Dictionary<string, List<string>>();

        if (!string.IsNullOrEmpty(accountValue))
        {
            if (provisionAccountTypeId == (int)ProvisionAccountTypeEnum.CD_IDENT && accountValue.Length != 5)
            {
                errors.Add(nameof(accountValue), new List<string> {"CD Ident requires a 5 digit account number"});
            }
            else if (provisionAccountTypeId == (int)ProvisionAccountTypeEnum.VP_Account && accountValue.Length > 15)
            {
                errors.Add(nameof(accountValue), new List<string> {"VP Account number has a max length of 15"});
            }
        }

        return errors;
    }
}
Step 2: Inject and Use the Service in Your Form Component

Next, inject this service into your form component (assuming you're using a framework like Blazor, which matches your HandleValidSubmit pattern) and replace the inline logic with a call to the service:

// At the top of your component (Blazor example)
@inject AccountValidationService _accountValidationService

// Inside your HandleValidSubmit method
_accountValidator.ClearErrors();
var validationErrors = _accountValidationService.ValidateAccount(
    SelectedAgreement.ProvisionAccountTypeId, 
    SelectedAgreement.Account
);

if (validationErrors.Any())
{
    _accountValidator.DisplayErrors(validationErrors);
    return false;
}

// Proceed with your normal submit logic...

Don't forget to register the service with your dependency injection container (e.g., in Program.cs for .NET apps):

builder.Services.AddScoped<AccountValidationService>();
Bonus: Optional Enhancements
  • Localize Error Messages: Move the hardcoded error strings into a resource file to support multiple languages easily.
  • Extend Rules: Add more account type validation cases to the service later without touching your form code.
  • Stronger Typing: Instead of passing an int for the account type, use the ProvisionAccountTypeEnum directly for type safety:
    public Dictionary<string, List<string>> ValidateAccount(ProvisionAccountTypeEnum accountType, string accountValue)
    {
        // Update checks to use the enum directly:
        if (accountType == ProvisionAccountTypeEnum.CD_IDENT && accountValue.Length != 5)
        {
            // ...
        }
    }
    

This approach keeps your form code focused on handling submission while centralizing reusable validation logic—perfect for avoiding duplicate code across your app, even with your existing data annotation setup.

内容的提问来源于stack exchange,提问作者Martin Andersen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:18:18