• How to use Model Validation in ASP.NET MVC

    by  • January 6, 2016 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET MVC • 0 Comments

    When an online customer fill a data entry form, then we as a web developer, have to ensure that submitted data is in correct format. For this purpose ‘Model Validation’ is used. Validation checks the accuracy of model’s representation of the real system. Model validation means the model possess the satisfactory range of accuracy. System.ComponentModel.DataAnnotations is the namespace which provide us validation attributes for validation checks on both server and client.

    Now lets look at the model named as ‘Book’. We add namespace System.ComponentModel.DataAnnotations and then add validation attributes for each model property that ensure the data submitted is in valid format. Model ‘Book’ is shown below with validation attributes.

    Book.cs

    In the above code, only some attributes like [Required] or [DataType(DataType.Date)] is needed and not additional code required here as we are using namespace System.ComponentModel.DataAnnotations.

    Now after adding a validation attributes in Book model class. We add a form in the AddBook.cshtml View file. Lets look on the AddBook.cshtml code.

    AddBook.cshtml

    In the above code we use @Html.ValidateSummary() helper method. This helper method is used to display validation errors.We add validation attribute for property ‘PublishDate’ as DataType(DataType.Data) and we use razor syntax in View as @Html.EditorFor(). ¬†@Html.EditorFor() is a unique type of helper method that determine itself that determine itself what there output will be. As in this case it shows us calendar to put date in that textbox so its magic. see the figure below;

    date

     

    Now we run our program and if customer submits the form without entering any data in any field then following validation errors will display.

    validation




    Namecheap.com

    Leave a Reply