Question

For some reason my client side validation does not seem to be working:

Here is my html:

@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{

<hr />

@Html.ValidationSummary(true)
<hr />

<p>
    <label>Select Client_ID: </label>
    <span class="field">
        <select name="clientId" id="clientId">
            @foreach (var item in Model.ClientId)
            {
                <option value="@item">@item</option>
            }
        </select>
    </span>
</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.name)</label>
    <span class="field">
        @Html.EditorFor(model => model.UserModel.name)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.name)

</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.password)</label>
    <span class="field">
        @*<input name="password" id="password" type="password" />*@
        @Html.EditorFor(model => model.UserModel.password)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.password)
</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.email)</label>
    <span class="field">
        @*<input name="email" id="email" type="email" />*@
        @Html.EditorFor(model => model.UserModel.email)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.email)
</p>

<p>
    <label>Select: </label>
    <span class="field">
        <select name="accessLevel" id="accessLevel">
            <option value="3">Company</option>
            <option value="5">End-User</option>
        </select>
    </span>
</p>

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

Here is my model:

 public class CreateUserModel
{
    [Required]
    [Display(Name = "Client_ID")]
    public string clientId { get; set; }

    [Required(ErrorMessage = "A name is required")]
    [MaxLength(20), MinLength(2, ErrorMessage = "Name must be 2 character or more")]
    [Display(Name = "Name")]
    public string name { get; set; }


    [Display(Name = "Email Address")]
    [Required(ErrorMessage = "Email is Required")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                        @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                        @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                        ErrorMessage = "Email is not valid")]
    public string email { get; set; }

    [Required]
    [MaxLength(20), MinLength(6, ErrorMessage = "Password Must be 6 or more chataters long")]
    [Display(Name = "Password")]
    public string password { get; set; }

    [Required]
    public int accessLevel { get; set; }
}

and I do have client side enabled in the webconfig:

 <appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

{EDIT} added rendered html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

<script src="/Scripts/modernizr-2.6.2.js"></script>

</head>
<body>
<script src="/Scripts/jquery.validate.js"></script>
<div class="jumbotron">
<h1>Add Users to the website</h1>
</div>
<form action="/Home/Create" method="post">    <hr />
<hr />

<p>
    <label for="UserModel_name">Name</label>
    <span class="field">
        <input type="text" name="name" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.name" data-valmsg-replace="true"></span>

</p>
<p>
    <label for="UserModel_password">Password</label>
    <span class="field">
        <input name="password" id="password" type="password" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.password" data-valmsg-replace="true"></span>
</p>
<p>
    <label for="UserModel_email">Email Address</label>
    <span class="field">
        <input name="email" id="email" type="email" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.email" data-valmsg-replace="true"></span>
</p>
<p>
    <label>Select: </label>
    <span class="field">
        <select name="accessLevel" id="accessLevel">
            <option value="3">Company</option>
            <option value="5">End-User</option>
        </select>
    </span>
</p>
<input type="submit" value="Submit" />
 </form>
    <hr />
    <footer>
        <p>&copy; 2014 - My ASP.NET Application</p>
    </footer>
</div>

<script src="/Scripts/jquery-2.1.0.js"></script>

<script src="/Scripts/bootstrap.js"></script>

No correct solution

OTHER TIPS

For some reason the Html helpers does not have generated validation attributes in the inputs (data-val="true" and the others), check that. Besides to check the order in which the javascript libraries are loaded:

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

Your problem is likely that you have jQuery at the bottom of your file, but you are putting jquery.validate at the top. jQuery has to come before jQuery.validate. I would suggest always putting jQuery in your header, not in the body, and it should be the first thing after modernizr.

Also, you do know that jQuery 2.x does not work with IE8 ore earlier, right?

It seems that your jquery.validate.js is in wrong position. It must be after main jquery ref.

For MVC 5, it should be as following:

_Layout.cshtml: (bottom of page)

<body>
...
...
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval") <!-- *required for client side validation! -->
@RenderSection("scripts", required: false)
</body>

where ~/bundles/jqueryval is defined in BundleConfig.cs: RegisterBundles() method:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate*"));

Use:

@Html.EditorFor

Instead of:

<input>

And of course you need the jquery.validate.* scripts

TRY THIS: Your validation is failing because you have hard-coded this JQuery link version at the bottom of your page, which likely has been updated to a newer version in your Scripts folder:

<script src="/Scripts/jquery-2.1.0.js"></script>

All you need to do is go to "Scripts", see if there is a "jquery-2.1.0.js" file or you updated JQuery to a newer version. Type in the newer version file name, if found, and retest. It should work now. As of this June 2017 we are on JQuery version 3.1.1

This happened to me and I was pulling my hair out till I realized I had updated JQuery and saw it removed the old version. I bet that's your issue. In case you are not doing this, I recommend you not follow the View Page templates that stick validation scripts in View Pages and instead create a simple usercontrol or masterpage or layout view page and stuff your JQuery links in there so they are shared universally by all project pages. The browser will naturally cache these pages the first time, so even if they aren't used on other pages they are not loaded again.

Not sure if this is being loaded dynamically (e.g loading a partial view with Ajax). If so then you need to parse the html with the validator on the success e.g. Use something like...

$.validator.unobtrusive.parse(".target");

E.g.

 function loadAPartialView(endPoint) {                    
                $.ajax({
                    url: endPoint,
                    type: 'GET',
                    cache: false,
                    success: function (result) {

                        $('.target').html(result);
                        $('.target').show();

                        // IMPORTANT. Next line is required to get the client side validation to run.
                        $.validator.unobtrusive.parse(".target");
                        $(".loadingMessage").hide(); 
                    },
                    error: function (result) {
                           // Error message... 
                           $(".loadingMessage").hide();

                    }
                });
            };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top