)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to enable the Unobtrusive Jquery validation for a form in MVC on page transfer?

Platform: ASP.NET MVC |
Control: General |
Published Date: February 19, 2015 |
Last Revised Date: May 8, 2019
Tags: general, mobile

Unobtrusive jquery validation for form

In MVC, form validation is achieved by using its built-in jquery unobtrusive validation. The form validation does not work when a page is transferred via the Ajax request. You can enable the validation in the viewtransfer event. To achieve this, refer to the following steps.

  1. Create a model file to the application. This consists of jquery validation rules. You can refer to the following code example. 

Sample.cs

public class Sample

    {

        [Required]

        public string Name { get; set; } 

        [Required]

        [EmailAddress]

        public string Email { get; set; }

    }

  1. Create the form with unobtrusive error message. Refer to the following code example.

Index.cshtml

<form>

    @Html.LabelFor(model => model.Name)

    @Html.TextBoxFor(model => model.Name)

    @Html.ValidationMessageFor(model => model.Name)

    <br />

    @Html.LabelFor(model => model.Email)

    @Html.TextBoxFor(model => model.Email)

    @Html.ValidationMessageFor(model => model.Email)

    <br />

    <input type="submit" value="Submit" />

</form>

  1. To enable form validation after the Ajax page transfer, add the following script code to the active page. This recalibrates all the validators of the form elements when content is added dynamically.

Script

 <script>

    $(document).bind("viewtransfer", function () {

        $('form').removeData('validator');

        $('form').removeData('unobtrusiveValidation');

        $.validator.unobtrusive.parse('form');

    });

</script>

 

2X faster development

The ultimate ASP.NET MVC UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon