Monday, December 5, 2016

MVC Validation

Using data annotations. Data annotations are nothing but attributes which applied on model properties.

This CustomerCode property is tagged with a Required data annotation attribute. If this model is not provided customer code, it will not accept it.

public class Customer
{
    [Required(ErrorMessage="Customer code is required")]
    public string CustomerCode
    {
        set;
        get;
    } 
}  

To display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%> 

In the controller, we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

public ActionResult PostCustomer(Customer obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Thanks");
    }
    else
    {
        return View("Customer");
    }
}

use the ValidationSummary method from the Html helper class to display all errors in one go

<%= Html.ValidationSummary() %>   

Others Data Annotation.

[StringLength(160)]public string FirstName { get; set; } //String Length
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; } //Email Regular Expression
[Range(10,25)]public int Age { get; set; } //Number in Range
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; } //string compare
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage; //get a error message, use Error corllection.
TryUpdateModel(NewCustomer); //Create model object yourself and call TryUpdateModel in controller to check the object valid or not.
ModelState.AddModelError("FirstName", "This is my server-side error."); //Add errors in the controller


2 Step to enable data annotation validation on client side.
  • Reference the JQuery files.
  • <script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
  • Call EnableClientValidation method.
  • <% Html.EnableClientValidation(); %> 

No comments:

Post a Comment