Data Annotations

Data Annotation is used for Data validation.

Data Annotation Validator Attributes

  • DataType
  • DisplayName
  • DisplayFormat
  • Required
  • ReqularExpression
  • Range
  • StringLength
  • MaxLength

Server side validation

Explicit Model Validation

Traditional way inject error in ModelState.

class HomeController : Controller
{
    [HttpPost]
    public ActionResult ExplicitServer(UserViewModel model)
    {
        //Write custom logic to validate UserViewModel
        if (string.IsNullOrEmpty(model.UserName))
        {
            ModelState.AddModelError("UserName", "Please enter your
           name");
        }
        if (!string.IsNullOrEmpty(model.UserName))
        {
            Regex emailRegex = new Regex(".+@.+\\..+");
            if (!emailRegex.IsMatch(model.UserName))
                ModelState.AddModelError("UserName", 
                    "Please enter correct email address");
        }

        if (ModelState.IsValid) //Check model state
        {
            //TO DO:
        }
    }
}

Model Validation with Data Annotation

[Required(ErrorMessage = "Please Enter Email Address")]
 [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
 [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
 public string UserName { get; set; }

Enable and disable client-side validation

protected void Application_Start()
{
 HtmlHelper.ClientValidationEnabled = true;
 HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}
@using MvcApp.Models
@{
 ViewBag.Title = "About";
 HtmlHelper.ClientValidationEnabled = false;
}

jquery.validate.unobtrusive.js

Microsoft introduced this plugin with ASP.NET MVC3 to apply data model validations to the client side.

results matching ""

    No results matching ""