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:
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; } }
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>();
- 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
intfor the account type, use theProvisionAccountTypeEnumdirectly 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

