MVC 4 Client side validation not working

2019-03-17 21:32发布

问题:

Trying to learn the basics of ASP.net MVC and cant quite understand why my client side validation isnt working.

I have this in both my web.config files (1 is global 1 is in the views folder)

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

I have this in my _layout.cshtmlfile

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")

This is my view model for which im testing registration:

public class RegisterVM
    {
        [Required(ErrorMessage="Username Required")]
        public string username { get; set; }

        [RegularExpression(@"((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})")]
        [Required(ErrorMessage="Password Required")]
        public string password { get; set; }

        [Compare("password", ErrorMessage="Passwords do not match")]
        public string passwordConfirm { get; set; }
    }

And this is my html

@using(@Html.BeginForm()){

    @Html.LabelFor( model => model.username)
    @Html.EditorFor( model => model.username)
    @Html.ValidationMessageFor( model => model.username)<br />

    @Html.LabelFor( model => model.password)
    @Html.PasswordFor( model => model.password)
    @Html.ValidationMessageFor( model => model.password)<br />

    @Html.LabelFor( model => model.passwordConfirm)
    @Html.EditorFor( model => model.passwordConfirm)
    @Html.ValidationMessageFor( model => model.passwordConfirm)<br />

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


}

Didn't want to post here, ive read a few topics on here related but cant seem to fix my issues, when i click submit it's making post/get requests.

回答1:

Feels like this should work, I think you need to load validate.min.js before validate.unobtrusive.min.js



回答2:

I had a similar problem and the only thing that fixed it was to manually call

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

before I press the submit button.

I finally put it in document ready callback.

$(function () {
    $.validator.unobtrusive.parse($('form'));
});


回答3:

In your page you have these two line in bottom of the page

please See carefully

@section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
}


回答4:

That's because you doesn't load jquery.validate.min.js before the unobtrusive one.



回答5:

$('#divParent').load("url",
                     function () {
                     $.validator.unobtrusive.parse($('form'));}
                );

Note: This is required if you are loading 'form' or 'PartialView' dynamically inside 'div' using ajax calls



回答6:

You need just reference these files on every page you need validation my friend!

<script src="~/Scripts/jquery.validate.js"></script>