In my MVC4 app, I’m trying to create a client side validator for some textboxes in a form. The form is contained in the Register.cshtml view (this view is automatically created by VS2010 when i make a new MVC4 with formsauthentication project).
The form already implements validation on Submit button, but I want a validator that acts as soon as focus leaves the textbox – should show me an inline error just next to the textbox, with a red font. if it validated ok, it should again show the message ‘ok’.
The problem: The .js validator doesn’t work. Firebug says:
$document is not defined.
$document.ready(
I also tried alert(), if i place it outside the document.ready function, it pops. when inside, it doesnt pop.
Code for registerForm.js:
$document.ready(
function ()
{
$('#registration form').validate
(
{
rules:
{
UserName: { required: true }
},
success: function (label)
{
label.Text('OK!').addClass('IsInputValid');
}
}
)
}
);
The bundle that adds this javascript is as follows:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/registerForm.js",
"~/Scripts/jquery.validate*"));
Finally, the view:
<div id="registration">
@using (Html.BeginForm()) {
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
What could prevent the js from working?
I’ve already spent about 5hours trying to figure this out. Please let me know if you have any suggestions,
Regards,
No need for JS here. And what everyone else is saying about $document not being the correct syntax, unless you have var
$document = $(document)defined somewhere.