问题描述
我将如何将 MVC 3 表单上的多个文本框视为一个文本框以进行验证?
How would I go about having multiple textboxes on an MVC 3 form treated as one for the purposes of validation?
这是一个简单的电话号码字段,其中一个用于区号的文本框,一个用于前缀和一个用于最后四位数字的文本框.
It's a simple phone number field with one textbox for area code, one for prefix and one for the last four digits.
实际上有两个验证要求:
There are really two validation requirements:
1) 它们都是必需的.2) 它们必须都包含整数.
1) They're all required.2) They must all contain integers.
现在对单个字段执行此操作很简单,但是如何使用 MVC 创建等效的 ASP.NET CustomValidator 以便我可以整体验证所有三个字段?
Now this is simple when doing it for individual fields but how can I create the equivalent of an ASP.NET CustomValidator with MVC so that I can validate all three fields as a whole?
推荐答案
我实际上最终实现了一个自定义的 ValidationAttribute
来解决这个问题,使用了 CompareAttribute
中提供的相同类型的逻辑code> 允许您使用反射来评估其他属性的值.这允许我在属性级别而不是模型级别实现这一点,并且还允许通过不显眼的 javascript 进行客户端验证:
I actually ended up implementing a custom ValidationAttribute
to solve this, using the same type of logic presented in CompareAttribute
that allows you to use reflection to evaluate the values of other properties. This allowed me to implement this at the property level instead of the model level and also allows for client side validation via unobtrusive javascript:
public class MultiFieldRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _fields;
public MultiFieldRequiredAttribute(string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (string field in _fields)
{
PropertyInfo property = validationContext.ObjectType.GetProperty(field);
if (property == null)
return new ValidationResult(string.Format("Property '{0}' is undefined.", field));
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
if (fieldValue == null || String.IsNullOrEmpty(fieldValue.ToString()))
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "multifield"
};
}
}
这篇关于多个字段的 MVC 表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!