Subashree Krishnan
Subashree Krishnan

Reputation: 44

How to validate the HTML controls with data annotations in MVC?

In .Net MVC. I have a html control. Inorder to bind it with the model property I am using name attribute. How do we get the validations(using data annotation) provided in the model class property into the html control?

In Cshtml

@using (Html.BeginForm("ClaimWarranty", "WarrentyClaim", FormMethod.Post, new{ enctype = "multipart/form-data" }))
            {
        <div class="form-group row">
         <label for="" class="col-md-2 col-form-label input-label">Email Address:</label>

        <div class="col-md-8">
        <input type="text" name="Emailaddress" class="form-control input-style" placeholder="[email protected]">
         </div>
                                            </div>
        <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" onclick="ValidateFileSize()" class="btn btn-default" />

                    </div>
                </div>
        }

    //The model class is below;
     public class ClaimWarranty
        {
     [Required(ErrorMessage = "Email ID is Required")]
            [DataType(DataType.EmailAddress)]
            [MaxLength(50)]
            [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
            public string Emailaddress { get; set; }
    }

I am using the name property to bind the text box to the model property .

<input type="text" name="Emailaddress" class="form-control input-style" placeholder="[email protected]"> 

How do I get the validations in the html control ,provided in the model class (using the data annotations) as shown above without using jquery validations or razor code?

Upvotes: 1

Views: 1657

Answers (2)

Johnny
Johnny

Reputation: 303

if(!ModelState.IsValid) 
{
   // you can get the error information from model state, convert it into list
   var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
                                    .SelectMany(E => E.Errors)
                                    .Select(E => E.ErrorMessage)
                                    .ToList();
   // now you have got the list of errors, you will need to pass it to view
   // you can use view model, viewbag etc
   ViewBag.ErrorList = validationErrors;
   return View();
}
else 
{
     // perform your business operation, save the data to database
     return View();
}

On View Page -

you have to add check for validation error list

if(ViewBag.ErrorList != null) 
{ 
    foreach(var errorMessage in ViewBag.ErrorList) 
    {
       // here you can display the error message and format in html
    }
}


Way you can display error on view page
1. @Html.ValidationSummary() - It will display summary of the validation errors
2. @Html.ValidationMessageFor(x => x.Emailaddress) - It will display error message 
   for specific property
3. you have to manually retrieve the error information from model state and then store it in list and pass to the view page.

Upvotes: 0

Nijin P J
Nijin P J

Reputation: 1322

In View

@model Demo.Models.Student
  
@using (Html.BeginForm("SaveStudent", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))   
{         
<div class="form-group">  
   @Html.LabelFor(model =>model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
   <div class="col-md-10">  
   @Html.EditorFor(model =>model.Name, new { htmlAttributes = new { @class = "form-control" } })  
   @Html.ValidationMessageFor(model =>model.Name, "", new { @class = "text-danger" })  
   </div>  
</div> 

    <div class="form-group">  
        <div class="col-md-offset-2 col-md-10">  
            <input type="submit" value="Create" class="btnbtn-primary" />  
        </div>  
    </div>  

}

In Model

public class Student
{
  [Required(ErrorMessage = "Please enter name"), MaxLength(30)]   
  public string Name { get; set; }
}

By default, ASP.Net MVC framework executes validation logic during model binding. In Controller side, we need to check

 if (ModelState.IsValid)  
  {  
  }

OR We can also check Individual validation, as shown below:

if (ModelState.IsValidField("LastName") == false) 

Upvotes: 1

Related Questions