Reader Level:
ARTICLE

Regular Expression Validator HtmlHelper for ASP .Net MVC

Posted by Shantanu Articles | ASP.NET MVC February 09, 2011
Sometimes, it is useful to use regular expressions for validations. The Regular Expression Validator HtmlHelper is designed to help developers accomplish this.
  • 0
  • 0
  • 19861
Download Files:
 


Purpose

Sometimes, it is useful to use regular expressions for validations. The Regular Expression Validator HtmlHelper is designed to help developers accomplish this. This Helper is useful if you want to perform server side operations (like fetching the Regular Expression and Error Message from a database or resource files) and want the validation part to be client-side using the JQuery validaton plugin.

Implementation

The Regular Expression Validator is an HtmlHelper built using Extension Methods.

public static MvcHtmlString RegularExpressionValidatorFor<TModel, TProperty>(this HtmlHelper<TModel> Html,
                            System.Linq.Expressions.Expression<Func<TModel, TProperty>> Expression,
                            string ValidationExpression, string ErrorMessage, bool AutoWireupValidateOnSubmit
                            )
        {}
        public static MvcHtmlString RegularExpressionValidator(this HtmlHelper Html,
                            string Name, string ValidationExpression, string ErrorMessage, bool AutoWireupValidateOnSubmit
                            )
        {}


regularexp.jpg

The Helper uses the JQuery validation plugin for client side validation. A custom rule (with the same name as the ControlID) is created which calls a javascript function that does the validation.

string OnInit = @"
                    function OnInit" + ControlID + @"() {

                        $.ajaxSetup({ cache: false });

                        jQuery.validator.addMethod("""
+ ControlID + @"""" + @", function(value, element) {
                            return RegexValidate('" + ControlID + @"');
                        }, '" + ErrorMessage + @"'); 
                    }
                "
;

The Javascript function which does the validation is as under

            string RegexValidate = @"
                function String.prototype.trim()
                {
                    return this.replace(/^\s*|\s*$/, '');
                }
                function RegexValidate(ControlID){
                    var RegexContainer = document.getElementById('RegexContainer' + ControlID);
                    var Control = document.getElementById(ControlID);
                    var Regex = RegexContainer.getAttribute('validationexpression');
                    //Helper will not validate if the input is an empty (or spaces only) string.
                    if (Control.value.trim() == '') return true;

                    if (Control.value.match(Regex) == null) { return false; } else { return true; }
                }"
;

If AutoWireupValidateOnSubmit is set to true, then a Handler is attached to the form Submit automatically. The JQuery validate function is called inside this handler.

                AutoWireup = @"function AutoValidateOnSubmit" + ControlID + @"()
                               {
                                    $(document).unbind('submit');
                                    $(document).bind('submit', function() {
                                        $('form').validate({
                                            rules: {
                                                "
+ Rules + @"
                                            }
                                        });
                                    });
                               }
                                "
;

If AutoWireupValidateOnSubmit is set to false, then Handler and the call to JQuery validate has to be done manually in the page. This is useful if it required to plug the Validator into an already existing validate call.

$(document).bind('submit', function () {
    $('form').validate({
        rules: {
            FirstName: { FirstName: true },
            LastName: { LastName: true },
            UserID: { UserID: true }
        }
    });
});

In the rules section, the rule has to be called as shown above. The RuleName created by the helper is the same as the ControlID. The syntax is

ControlID: { RuleName: true }

Sample Usage

Add a reference to the Toolkit.Web.Mvc.dll.

Then, in the page

Import the namespace

<%@ Import Namespace="Toolkit.Web.Mvc"  %>

Add JQuery to the page

<script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>

Add the JQuery validation plugin

<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>

Use the validator

<%: Html.TextBoxFor(m => m.FirstName)%>
<%: Html.ValidationMessageFor(m => m.FirstName)%>
<%: Html.RegularExpressionValidatorFor(m => m.FirstName, @"^[a-zA-Z]+$", "Invalid First Name", false)%>

<%: Html.TextBoxFor(m => m.LastName)%>
<%: Html.ValidationMessageFor(m => m.LastName)%>
<%: Html.RegularExpressionValidatorFor(m => m.LastName, @"^[a-zA-Z]+$", "Invalid Last Name", false)%>

<%: Html.TextBoxFor(m => m.UserID) %>
<%: Html.ValidationMessageFor(m => m.UserID) %>
<%: Html.RegularExpressionValidatorFor(m => m.UserID, "^[a-zA-Z0-9]+$", "Invalid User ID", false) %>

In this example, we will set AutoWireupValidateOnSubmit to false and manually add the rules to a pre-existing JQuery validate call in the page

$(document).bind('submit', function () {
   $('form').validate({
      rules: {
         FirstName: { FirstName: true },
         LastName: { LastName: true },
         UserID: { UserID: true }
      }
   });
});

The advantage of this validator is that it performs client-side validation using the JQuery validation plug-in.

This Helper is useful if you want to perform server-side operations (like fetching the Regular Expression and Error Message from a database or resource files) and want the validation part to be client-side using the JQuery validaton plugin.


Screenshot

regularExp1.gif

COMMENT USING

Trending up