Validation
Validation
Model View
Implement validation (Con.)
ModelState.IsValid:
determines that whether
submitted values satisfy
All the DataAnnotation
Validation attributes applied to model properties.
ModelState
• Model state represents errors that come from two
subsystems: model binding and model validation.
• Errors that originate from model binding are
generally data conversion errors.
– For example, an "x" is entered in an integer field.
• Model validation occurs after model binding and
reports errors where data doesn't conform to business
rules.
– For example, a 0 is entered in a field that expects a rating
between 1 and 5.
Implement Validation (Con.)
• Method Parameters:
– The first Parameters :is a lambda expression to specify a
property for which we want to show the error message.
– The second parameter is for custom error message
– The third parameter is for html attributes like css, style etc
ValidationMessageFor (Con.)
Model
View
ValidationMessageFor (Con.)
• Custom Error Message
– You can display your own error message instead of
the default error message , using:
• DataAnnotations Attribute:
[Required(ErrorMessage="Please enter student name.")]
public string StudentName { get; set; }
• ValidationMessageFor() Method:
@Html.Editor("StudentName") <br />
@Html.ValidationMessageFor(m => m.StudentName,
"Please enter student name.", new { @class = "text-
danger" })
ValidationSummary
• The ValidationSummary helper
method generates an unordered
list (ul element) of validation
messages that are in the
ModelStateDictionary object
• Method Signature:
ValidationSummary (Con.)