jQuery custom validation problem in MVC 3

2019-08-06 05:18发布

问题:

I am using MVC3. I want to add a custom checking in client side when submitting the page..But doing so the default validation is not working...

@using (Html.BeginForm())

{

 @Html.TextBoxFor(model => model.Title, new { maxlength = 250 , style = "width:450px;" })
 @Html.ValidationMessageFor(model => model.Title)

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

}

When i click the submit button I write a validation below

 $('#submit').click(function () {/*code for validation*/ if not satisfied then  return false; else return true; }

This is working fine.In case of return false , the default validation provided by model is not working ie. @Html.ValidationMessageFor(model => model.Title) this code is not working[Error message not showing].How to validate the default validation when click the button?

回答1:

try adding the following line to your view. Html.EnableClientValidation();

Check that Client validation is enabled in web.config:

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

You will need to reference the following scripts:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/>

This link will give you a bit of background as to how it works. http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html



回答2:

It won't work since the unobtrusive validation in mvc is handled internally in this script: jquery.validate.unobtrusive.js. I think your choices are to either build your own validation all together ignoring build in validation using annotations or see if you can add your validation rule in the script mentioned earlier. You can look at a question I posted that deals with a similar issue, not quiet but maybe it can give you an idea of what you need to do. Hope this helps, here is the post:

Integrating qTip with MVC3 and jQuery Validation (errorPlacement)

EDIT: The reason it won't work its cause the script mentioned above validates the form and when it fails, add the error messages. Hence, error messages are only shown when an error is found within the rules on the script, not on external validations like the one you mentioned.