-
Client Side Validation For DataType Attribute in ASP.NET MVC3
Posted on November 20th, 2012 Add commentsAfter Microsoft announced ADO.NET Entity Framework 4.1, database design becomes to very easy via Code First approach. And the DataType Attribute from “System.ComponentModel.DataAnnotations” namespace has been used very popular during Code First. Here are some examples:
12345678public class User{[DataType(DataType.EmailAddress)]public string UserEmail { get; set; }[DataType(DataType.Date)]public DateTime CreateDate { get; set; }}But be noticed, this validation of attribute only fires when you check “ModelState.IsValid” property in Controller or calling “SaveChanges()” in Entity Context, not in the client side. fortunately, JQuery has all the client side validation for those data types. So, the lazy way is just connect them together.
First we need to use “DataAnnotationsModelValidator” class from “System.Web.Mvc” namespace:12345678910111213141516171819202122232425262728293031323334public class DataTypeAttributeAdapter : DataAnnotationsModelValidator<DataTypeAttribute>{public DataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute): base(metadata, context, attribute){}public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(){var rule = new ModelClientValidationRule();rule.ErrorMessage = this.ErrorMessage;switch (this.Attribute.DataType){case DataType.EmailAddress:rule.ValidationType = "email";//from JQuery validate functionbreak;case DataType.Url:rule.ValidationType = "url";//from JQuery validate functionbreak;case DataType.Currency:rule.ValidationType = "currency";//from JQuery validate functionbreak;case DataType.Date:rule.ValidationType = "dateus";//from JQuery validate functionbreak;case DataType.Time:rule.ValidationType = "time";//from JQuery validate functionbreak;default:return new ModelClientValidationRule[0];}return new[] { rule };}}Then, we need to register this validation to JQuery in “Global.asax.cs”, under function “Application_Start()”:
123DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(System.ComponentModel.DataAnnotations.DataTypeAttribute),typeof(CAMSEntityDataLib.DataTypeAttributeAdapter));Rebuild your MVC3 project, and now you have client side validation when you using “HtmlHelperFor” for your Model properties in Razor!
641 views
Leave a Reply
Be the First to Comment!