fuzzi
fuzzi

Reputation: 2277

Client-side validation in ASP.NET MVC project is not validating the rules

I am using the following JS.fiddle of client-side validation within my project. I have implemented this example as my javascript. http://jsfiddle.net/rtglenn/VwPaR/

Currently, the fields are highlighting green when active and staying green. However, they are not displaying red if one of the rules is broken.

Here is my View:

@using (Html.BeginForm()
{ 
<div class="form-horizontal">
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group has-feedback">
        <div class="float:left"> 
            @Html.Label("First Name:", htmlAttributes: new { @class = "control-label col-md-2", @for = "fname" })
            <div class="col-md-3">
                 @Html.EditorFor(model => model.Person.fName, new { htmlAttributes = new { @class = "form-control" }, name = "fname", id = "fname" })
                 @Html.ValidationMessageFor(model => model.Person.fName, "", new { @class = "text-danger" })
            </div>
        </div>

Any help on this issue would be greatly appreciated. I have checked that my referenced scripts are in the correct order.

Upvotes: 0

Views: 276

Answers (1)

Brett Caswell
Brett Caswell

Reputation: 730

Look at the output of @Html.EditorFor(model => model.Person.fName, new { htmlAttributes = new { @class = "form-control" }}), your input name attributes are being assigned the values Person.fName and Person.lName, respectfully.

Your rules need to correlate to those name values.

 rules: {
            "Person.fName" : {
                minlength: 3,
                maxlength: 15,
                    required: true
                },
            "Person.lName" : {
                minlength: 3,
                maxlength: 15,
                required: true
            }
        },

for visual feedback, add this to your css:

.form-control.has-error input,
.has-error input 
{
    background-color:red;
    color:white;
}

Of course, there are alternative validation frameworks and methodologies. One of which ships with MVC: Unobtrusive Client Validation in ASP.NET MVC 3 (older post).

Related SO Q&A: What is jQuery Unobtrusive Validation?

Upvotes: 1

Related Questions