The ASP.NET MVC Framework validates any data passed to the controller action that is executing, It populates a ModelState object with any validation failures that it finds and passes that object to the controller. Then the controller actions can query the ModelState to discover whether the request is valid and react accordingly.
I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState object and another uses the Data Annotation API to validate the model data.
Approach 1 - Manually Add Error to ModelState object
I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following,
After that I create a controller action in User Controller (UserController.cs under Controllers folder). That action method has logic for the required validation for Name and Email validation on the Email field. I add an error message on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the model.
Thereafter I create a view (Index.cshtml) for the user input under the User folder.
I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState object and another uses the Data Annotation API to validate the model data.
Approach 1 - Manually Add Error to ModelState object
I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following,
- namespace ServerValidation.Models
- {
- public class User
- {
- public string Name
- {
- get;
- set;
- }
- public string Email
- {
- get;
- set;
- }
- }
- }
- using System.Text.RegularExpressions;
- using System.Web.Mvc;
- namespace ServerValidation.Controllers
- {
- public class UserController: Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Index(ServerValidation.Models.User model)
- {
- if (string.IsNullOrEmpty(model.Name))
- {
- ModelState.AddModelError("Name", "Name is required");
- }
- if (!string.IsNullOrEmpty(model.Email))
- {
- string emailRegex = @ "^([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})(\]?)$";
- Regex re = new Regex(emailRegex);
- if (!re.IsMatch(model.Email))
- {
- ModelState.AddModelError("Email", "Email is not valid");
- }
- } else {
- ModelState.AddModelError("Email", "Email is required");
- }
- if (ModelState.IsValid)
- {
- ViewBag.Name = model.Name;
- ViewBag.Email = model.Email;
- }
- return View(model);
- }
- }
- }
- @model ServerValidation.Models.User
- @ {
- ViewBag.Title = "Index";
- }
- @using(Html.BeginForm())
- {
- if (@ViewData.ModelState.IsValid)
- {
- if (@ViewBag.Name != null)
- { < b >
- Name: @ViewBag.Name < br / >
- Email: @ViewBag.Email < /b>
- }
- } < fieldset >
- < legend > User < /legend> < div class = "editor-label" >
- @Html.LabelFor(model => model.Name) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.Name)
- @if(!ViewData.ModelState.IsValid)
- {
- < span class = "field-validation-error" > @ViewData.ModelState["Name"].Errors[0].ErrorMessage < /span>
- }
- < /div> < div class = "editor-label" >
- @Html.LabelFor(model => model.Email) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.Email)
- @if(!ViewData.ModelState.IsValid)
- {
- < span class = "field-validation-error" > @ViewData.ModelState["Email"].Errors[0].ErrorMessage < /span>
- }
- < /div> < p >
- < input type = "submit"
- value = "Create" / >
- < /p> < /fieldset>
No comments:
Post a Comment