您可以创建一个自定义验证属性,通过检查存储在数据库中的元数据进行验证。自定义验证属性易于创建,只需扩展System.ComponentModel.DataAnnotations.ValidationAttribute
和覆盖该IsValid()
方法。
要获得适用于 jQuery 验证的客户端规则,您需要为扩展的自定义验证属性的类型创建一个自定义适配器System.Web.Mvc.DataAnnotationsModelValidator<YourCustomValidationAttribute>
。然后这个类需要在OnApplicationStart()
你的方法中注册Global.asax
。
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(YourCustomValidationAttribute), typeof(YourCustomAdapter));
这是一个示例适配器:
public class FooAdapter : DataAnnotationsModelValidator<FooAttribute>
{
/// <summary>
/// This constructor is used by the MVC framework to retrieve the client validation rules for the attribute
/// type associated with this adapter.
/// </summary>
/// <param name="metadata">Information about the type being validated.</param>
/// <param name="context">The ControllerContext for the controller handling the request.</param>
/// <param name="attribute">The attribute associated with this adapter.</param>
public FooAdapter(ModelMetadata metadata, ControllerContext context, FooAttribute attribute)
: base(metadata, context, attribute)
{
_metadata = metadata;
}
/// <summary>
/// Overrides the definition in System.Web.Mvc.ModelValidator to provide the client validation rules specific
/// to this type.
/// </summary>
/// <returns>The set of rules that will be used for client side validation.</returns>
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(
String.Format("The {0} field is invalid.", _metadata.DisplayName ?? _metadata.PropertyName)) };
}
/// <summary>
/// The metadata associated with the property tagged by the validation attribute.
/// </summary>
private ModelMetadata _metadata;
}
如果您想异步调用服务器端验证,这也可能很有用http://msdn.microsoft.com/en-us/library/system.web.mvc.remoteattribute(v=vs.108).aspx