Monday 19 August 2013

C# Tips : RegularExpression Validation using Annotations in ASP.Net MVC framework

Click Here to MVC_Regular_Expression_ValidationUsingAnnotations.zip Example.

We can do Regular Expression or REGEX validation using Annotations in MVC. We can use "RegularExpression" attribute for validation. In this attribute we specify Regular Expression string.

We can also specify our custom error messages for that we need to set "ErrorMessage" Property in "RegularExpression" attribute.

Here is example for this.


In this example we take "Email" Address validation using REGEX. If user enter email address, which is not in proper format at that time our validation message display on screen.

        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
        ErrorMessage="Email Address is not in proper format.")]
        public string Email { get; set; }

At the view side we have to add this code :

        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email,"", new { style="color:red"})

Here is Code for this. Model (Customer.cs):

    public class Customer
    {
        public int CustomerID { get; set; }

        [Required]
        [StringLength(20,MinimumLength=2)]
        public string FirstName { get; set; }

        [StringLength(10)]
        public string LastName { get; set; }

        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
        ErrorMessage="Email Address is not in proper format.")]
        public string Email { get; set; }

    }

Output :


Below are the books that you would like :

No comments:

Post a Comment