Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Client side validation not working

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.

like image 457
Larry Avatar asked May 29 '13 10:05

Larry


2 Answers

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

like image 50
Adil Avatar answered Nov 10 '22 07:11

Adil


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'));
});
like image 10
Gudradain Avatar answered Nov 10 '22 08:11

Gudradain