Monday 4 March 2013

ASP.NET MVC Model Validation


Model Validation: 
Validations are required for ensuring that the received data is valid and correct so that we can do the further processing with the data.

Validate in action method: We can validate model in action method. We can check the values of properties of the model object and register any errors we find with the ModelState property.
We can check to see whether the model binder was able to assign a value to a property by using the ModelState.IsValidField method. We do this make sure that the model binder was able to parse the value the user submitted; so that can perform additional checks.

Example:

if (string.IsNullOrEmpty(model.UserName))
{
      ModelState.AddModelError("UserName", "Please enter your user name");
}

if (!model.TermsAccepted)
{
      ModelState.AddModelError("TermsAccepted", "You must accept the terms");
}

if (ModelState.IsValid)
{
      //send model for further processing
}

ValidationSummary: The validation summary displays the error messages that we registered with the ModelState in our action method. There are a number of overloaded versions of the ValidationSummary method.

Method
Description
Html.ValidationSummary()
Generates a summary for all validation errors.
Html.ValidationSummary(bool)
If the bool parameter is true, then only model-level errors are displayed. If the parameter is
false, then all errors are shown.
Html.ValidationSummary(string)
Displays a message before a summary of all the validation errors.
Html.ValidationSummary(bool,string)
Displays a message before the validation errors. If the bool parameter is true, only model-level errors will be shown.


ValidationMessage: The Html.ValidationMessageFor helper displays validation errors for a single model property.
@Html.ValidationMessageFor(m => m.UserName)

Validation in the Model Binder: The default model binder performs validation as part of the binding process. The model binder performs some basic validation for each of the properties in the model object. If value has not been supplied or value that cannot be parsed into the model property type. DefaultModelBinder, provides us with some useful methods that we can override to add validation to a binder. Find detail in below table.

Method Name
Description
Default Implementation
OnModelUpdated
Called when the binder has tried to assign values to all of the properties in the model object. Model level validation.
Applies the validation rules defined by the model metadata and registers any errors with ModelState.
SetProperty
Called when the binder wants to apply a value to a specific property. Property level validation
Required or not valid message will show.


Data Annotations: The MVC Framework supports the use of metadata to express model validation rules. We can easily add validation to our application by including Data Annotations namespace and use attributes to our model classes. Data Annotations allow us to describe the rules we want applied to our model properties, and ASP.NET MVC will take care of enforcing them and displaying appropriate messages to our users. There is number of attribute classes which inherits validation attribute class, use to manage different types of validation.

Some of important build in data annotation attributes are:

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • RegularExpression – Validate input value as per defined regular expression
  • Compare – Two property must have same value.



Custom validation class: We can also create custom validation attribute by deriving from the ValidationAttribute class and implementing our own validation logic. We can override the IsValid method of the base class, this method get called by binder while passing value provided by user as the parameter.

Example:
public class MustBeTrueAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }
    }

[Display(Name = "I accept the terms & conditions")]
[MustBeTrue(ErrorMessage = "You must accept the terms")]
public bool TermsAccepted { get; set; }


Model Validation Attribute: We can also create a custom attribute at model level instead of property level. Model validator attribute will use only if property-level attributes does not register a validation error. We must apply a model validation attribute to the model class itself.

Example:
public class RegisterValidatorAttribute : ValidationAttribute
    {
        public RegisterValidatorAttribute()
        {
            ErrorMessage = "Please enter valid email";
        }

        public override bool IsValid(object value)
        {
            RegisterModel model = value as  RegisterModel;

            if (model.Email.Contains("test") || model.Email.Contains("test.com"))
            {
                return false;
            }
            return true;
        }
    }

[RegisterValidator]
public class RegisterModel


Client-Side Validation: In web application user expect immediately validation, without having to submit data to the server. This is client site validation and usually we implement JavaScript for this. This allow user to correct data before sending to the server for further processing.
The MVC Framework supports unobtrusive client-side validation. The term unobtrusive means that validation rules are expressed using attributes added to the HTML elements that we generate. These are interpreted by a JavaScript library that is included as part of the MVC Framework, which uses the attribute values to configure the jQuery Validation library, which does the actual validation work. There are few advantages using this approach.


  • We do not have to include client-side validation logic into our views
  • If JavaScript disabled in browser then server side validation will fire in same manner.
  • Mitigate the effect of browser inconsistencies and behaviors.


Enable/Disable Client validation: Developer can enable and disable client side validation by setting in web.config. By default it’s enabled.

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 </appSettings>

Both of these settings must be true for client-side validation to work. We can also set value programmatically like in global.asax page application start method.

protected void Application_Start()
{
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

We can enable or disable client-side validation for individual views as well by setting above value in view page.

In addition to the configuration settings, we must references three specific JavaScript libraries.

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

After all above setting client side validation will start to work based on applied metadata attributes in model properties such as Required, Range, Regular Expression and String Length.
Client side validation works faster and also perform validation on key stroke like key press or focus change.

In MVC Framework validation rules are expressed using HTML attributes. MVC client-side validation is that the same attributes we use to specify validation rules are applied at the client and at the server.  

Example:
Without validation attribute:
public string UserName { get; set; }
Output:
<input id="UserName" name="UserName" value="" type="text">

With validation attribute:
[Required]
public string UserName { get; set;
Output:
<input id="UserName" name="UserName" value="" type="text" data-val-required="The User name field is required." data-val="true">

Note: The MVC client-validation features are built on top of the jQuery Validation library; developer can use the Validation library directly and ignore the MVC features if required. The MVC client-validation features hide the JavaScript, and they have the advantage of taking effect for both client- and server-side validation.

Example:

<script type="text/javascript">
$(document).ready(function ()
{
    $('form').validate({
    errorLabelContainer: '#validtionSummary',
    wrapper: 'li',
    rules: {
        UserName: {
            required: true,
        }
    },
    messages: {
        UserName: "Please enter your user name"
    }
    });
});
</script>


The jQuery Validation library supports some more complex validation rules like email, url, date, number, digits and credit card or we can create new rules.

Creating attributes for client-side validation: To enable client-side validation, we must implement the IClientValidatable in model attribute class. We can create custom validation attributes that work in the same way as the built-in ones and that trigger client- and server-side validation.

The interface defines one method, GetClientValidationRules, which returns an enumeration of
ModelClientValidationRule objects. Each ModelClientValidationRule object describes the client-side validation rule that we want to apply, the error message to display when the rule is broken, and any parameters that the rule needs to operate.

Example:
Example to create a new rule called checkboxmusttrue to ensure that a checkbox is checked.
Developer has to add custom jQuery validation rule to unobtrusive adaptor.

<script type="text/javascript">

    jQuery.validator.unobtrusive.adapters.add("checkboxmusttrue", function (options) {
        if (options.element.tagName.toUpperCase() == "INPUT" &&
options.element.type.toUpperCase() == "CHECKBOX") {
            options.rules["required"] = true;
            if (options.message) {
                options.messages["required"] = options.message;
            }
        }
    });
</script>

public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return value is bool && (bool)value;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new ModelClientValidationRule[] {    new ModelClientValidationRule {
            ValidationType = "checkboxmusttrue",
                    ErrorMessage = this.ErrorMessage
            }};
        }
    }

15 comments:

  1. Hi, Nice description about ASP.NET MVC Model Validation .Thanks, its really helped me......

    -Aparna
    Theosoft

    ReplyDelete
  2. Excellent Post. Also visit http://www.msnetframework.com/#aspnet.php

    ReplyDelete
  3. What if your email is ChuckTesta@aol.com??

    ReplyDelete
  4. Its such as you read my brain! You appear to understand a lot about this, like you wrote the e-book in it or something. I believe that you simply could do with a few % to force the message house a bit, however other than that, this is wonderful blog. A great read. I'll certainly be back.

    Best and Excellent Kids Website Design Services in Affordable Price by Optimized360.

    ReplyDelete
  5. Thank you for your guide to with upgrade information.
    Dot Net Online Course Bangalore

    ReplyDelete

  6. Thanks for this for this article
    pleas share more articles about this
    my website talking about home improvement you can visite it from this url
    تنظيف افران بمكة
    شركة تنظيف افران بمكة

    ReplyDelete