我想向MVC Core 2.2中的可为空的整数字段添加自定义验证。到目前为止,我在实现它时遇到两个问题:
我已经尝试过的:
我要验证的整数字段
[Display(Name = "Page number")]
[CheckIsNumber(ErrorMessage = "Only numbers please.")] //Custom Validator
[Range(1, 9999, ErrorMessage = "Page number too long.")]
public int? Pagenumber { get; set; }
我的自定义验证器
public class CustomValidation
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
public sealed class CheckIsNumber : ValidationAttribute
{
protected override ValidationResult IsValid(object numbFromTextfield, ValidationContext validationContext)
{
if (numbFromTextfield != null)
{
string valNumb = numbFromTextfield.ToString();
bool isNumeric = int.TryParse(valNumb, out int n);
if (isNumeric)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Only numbers please.");
}
}
return ValidationResult.Success;
}
}
}
视图
<div class="form-group">
<label asp-for="Book.Pagenumber"></label>
<input asp-for="Book.Pagenumber" class="form-control" maxlength="4" />
<span asp-validation-for="Book.Pagenumber" class="alert-danger"></span>
</div>
// type="number" is also not helpful
如前所述,当我输入数字后跟字符时,只会得到默认错误消息。 (Example:值“ 4r”对于页码无效。)
仅当我在字段中键入数字时,才会调用自定义验证。
我想要实现的是对可为空的整数字段进行适当的自定义验证,并且我希望摆脱默认错误消息。我怎么做? 谢谢!