简体   繁体   中英

Asp.Net MVC validation messages overriding client side validations

In my Asp.Net Mvc application I have a scenario where I have to

  1. Check if control value is not null
  2. value entered in control is not "Search"

How can I achieve this with validation attributes?

I tried [Required] attribute on top of modal property and wrote a client side validation for "search". But error message shown by [required] attribute is overriding client side validation. any help?

        $.validator.addMethod("ruleName", function (value, element, params) {
            var a = this.optional(element);
            var b = value != params;
            return a || b;
        }, "error");

        $("#x").rules("add", {
            ruleName: "search"
        });

1,add a rule,write function to check
2,add the rule to input which you want
check the doc http://jqueryvalidation.org/documentation/

Don't write any custom validation code yourself, the MVC framework can do all this for you.

First, Make sure you include the following on your layout:

<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

And check that the following is set in your web.config:

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

Your form should be something like this:

@Html.TextBoxFor(Model => Model.EditPostViewModel.Title)
@Html.ValidationMessageFor(Model => MOdel.EditPostViewModel.Title)

And now it should all work automagically for you, no need to write custom validations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM