Tuesday, February 5, 2013

ASP.NET MVC: Custom unobtrusive validation

Sometimes becomes necessary to create custom validation attribute using custom regular expression. Obviously, we want to keep the client side validation and to make use of our custom regular expression on client side.

First of all we need to define a custom regular expression attribute:

public class CustomRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
   {
       public CustomRegularExpressionAttribute(string pattern) : base(pattern)
       {
       }

       public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
       {
           yield return new ModelClientValidationRegexRule(ErrorMessage, Pattern);
       }
   }

As you may notice our custom attribute inherits from RegularExpressionAttribute class and IClientValidatable interface. The last one will allow us to pass our regular expression pattern to the client side, by implementing the GetClientValidationRules method.

Second step is to implement custom validation attribute:

public class LoginAttribute : CustomRegularExpressionAttribute
   {
       public LoginAttribute()
           : base("^[a-zA-Z0-9\\._\\-]{6,24}$")
       {
           ErrorMessage = “Login";

       }
   }

This regular expression is just an example, it may, and probably will be more complicated, but in this case let’s just leave it as it is.

Now it is possible to use this custom attribute in a normal way in some kind of a view model:

public class TestModel
   {
       [Login]
       public string Login { get; set; }

       ...
   }

Finally we can use our model in view to create the required textbox with all necessary validation:

…
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
…
<div>
 @Html.TextBoxFor(m => m.Login)
 @Html.ValidationMessageFor(m => m.Login)
</div>

No comments :

Post a Comment