代码示例:
public class MyCustomValidator { public static ValidationResult Validate(string value, int maxLength) { if (string.IsNullOrEmpty(value) || value.Length > maxLength) return new ValidationResult("输入不能为空且长度不超过 " + maxLength + "。"); else return ValidationResult.Success; } }
public class ValidationResult
{
public bool IsValid { get; }
public string ErrorMessage { get; }
public ValidationResult(bool isValid, string errorMessage = null)
{
IsValid = isValid;
ErrorMessage = errorMessage;
}
public static ValidationResult Success { get; } = new ValidationResult(true);
}
@using System.ComponentModel.DataAnnotations @using MyApp.Shared
@code { private readonly MyModel Model = new MyModel();
private class MyModel
{
[MyCustomValidator]
[Required]
public string Email { get; set; }
}
}
public class MyCustomValidatorAttribute : ValidationAttribute { public override bool IsValid(object value) { return MyCustomValidator.Validate(value?.ToString(), 10).IsValid; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return MyCustomValidator.Validate(value?.ToString(), 10);
}
}
public class MyCustomValidator { private int maxLength;
public MyCustomValidator(int maxLength)
{
this.maxLength = maxLength;
}
public ValidationResult Validate(string value)
{
if (string.IsNullOrEmpty(value) || value.Length > maxLength)
return new ValidationResult("输入不能为空且长度不超过 " + maxLength + "。");
else
return ValidationResult.Success;
}
}
@using MyApp.Shared