Monday, April 21, 2014

MVC4 Validation (Client Side) using Ajax



Requirement: Validate the input by the user on client side.




Solution:
In the web.config check if the namespace is there, if not add it
<add namespace="System.Web.Mvc.Ajax" />

In the View add the following:
@section Scripts
{
    @Scripts.Render("~/bundles/jqueryval")
}



Add the “validationMessageFor” Html Helper like this-
<table width="100%">
  <tr>
    <td> 
      <div>First Name</div>                                                              
      <div>@Html.EditorFor(model =>  @item.FName)</div>
           @Html.ValidationMessageFor(model => @item.FName)
                                 
                                                                                   
                                          
      <div>Last Name</div>
      <div>@Html.EditorFor(model => @contact.LName)</div>
           @Html.ValidationMessageFor(model => @contact.LName)
     </td>
    </tr>                                                                                              
    <tr>
      <td><input type="submit" title="Save" /></td>
    </tr>
  </table>

In the Model:
[Required( ErrorMessage = "First Name is required.") ]
  public String FName { get; set; }

[Required]
   public String LName { get; set; }

[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                   @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                   ErrorMessage = "Email is not valid")]
   public String Email { get; set; }

//other way of using Email data annotation
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
   public String OtherEmail { get; set; }

      
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Please enter proper phone
                   number.")]                   
   public String Mobile { get; set; }


[RegularExpression(@"^(\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1}
                   *\d{1}[A-Z]{1}\d{1})$", ErrorMessage = "Invalid Zip")]           
   public String Postal { get; set; }

      

No comments:

Post a Comment