Client Side Required Field Validator Sample in MVC: Day 26

In this article we will see how to apply a required field validator from the client side in MVC.

  1. Create a MVC project from the "Empty" template.

  2. Right-click on "Models", select "Add" >> "Class…"

    add new class

  3. Name the class as "Employee" and click on the "Add" button.

    type class name

  4. In the employee class create employee properties like EmployeeId, FirstName, LastName and so on.

    employee code

  5. Now add a controller. Right-click on "Controllers", select "Add" >> "Controller…".

    add new controller

  6. Select "MVC 5 Controller - Empty" to add an empty controller.

    Click on the "Add" button.

    mvc5 empty controller

  7. Name the controller as in the following:

    add controller name

  8. Now add a view. Right-click on the "Index" action method and select "Add View…".

    add view

  9. Name the view as "Index".

    Select "Empty (without model)" from the template.

    Click on the "Add" button.

    add view name

  10. Now add two action result methods to the employee controller with the same name. One is for HttpGet and the other is for HttpPost. In the HttpPost "Create" method pass an Employee class object as a parameter. When we press the submit button it will call this HttpPost method.

    action result

  11. To add a view for the "Create" method, right-click on the "Create" action result method and select "Add View…".

    employee controller

  12. Name the view as "Create".

    From the model class drop down, select "Employee" as model.

    Click on the "Add" button.

    another view

  13. It will automatically create a view from the model.

    view from model

  14. Add a new folder to the root directory. Right-click on the project, select "Add" >> "New Folder".

    add new folder

  15. Name the folder as "Scripts".

    script

  16. Add the highlighted four ".js" files to the script folder.

    jquery

  17. Add a reference of these JavaScript files to the head section of create.cshtml.

    view port

  18. Add the "[Required]" attribute to the field that you want to make mandatory for insertion. The required attribute requires the "System.ComponentModel.DataAnnotations" namespace.

    employee class

  19. Run the project and call the "Create" action method of the Employee controller from the browser.

    employee

  20. Now do not fill in the form and press the "Create" button and you can see the error message against the fields where we set the "Required" attribute in the model.

    require field

    << Strongly Typed View Create Sample in MVC: Day 25

Up Next
    Ebook Download
    View all
    Learn
    View all