Home  >  Article  >  Web Front-end  >  Modify the default verification method in jQuery Validation_jquery

Modify the default verification method in jQuery Validation_jquery

WBOY
WBOYOriginal
2016-05-16 17:56:201117browse

In a recent project, I used jQuery Validation to verify the date. The problem I encountered and an unexpected situation was that in the ASP.NET MVC 3 project, for element, if the form's valid method is called to verify the form, although I did not add date verification settings, just type="date", it still calls the date verification logic to verify whether the date format is correct. This is originally a good behavior, but the problem is that the date formats it supports are limited. You will know by reading the code of jQuery Validation (of course, it is also explained in the document). For "date", date validation only uses Javascript's built-in processing to verify. Reflected in the code, it is to see whether new Date (date string) can succeed. On my computer, entering the date "9/5/2012" passes, but "2012-9-5" fails, which is obviously also a correct format. I need to change or improve this behavior. How to do it?

Of course, we can modify the source code of jQuery Validation, but first of all, I am quoting the code on the CDN. Secondly, as a public library, I think it is best not to change it yourself. As time goes by, maybe we We had forgotten to modify it, and when the official version was updated, we took it down and updated it, and as a result, our own modifications were overwritten. A better way is to patch it and replace the date verification function with our own from the outside. Perhaps thanks to the fact that Javascript's OO is not that thorough, the built-in validation methods are not changed into protected/private. After reading the source code, the replacement method is very simple. After quoting the source code of jQuery Validation, replace it like this:

Copy code The code is as follows:

$.validator.methods.date = function ( value, element)
{
// The Date.parse function comes from another library that handles dates
return this.optional(element) || Date.parse(value) != null;
};

In addition, the same method can be used to replace the default message, such as:
Copy code The code is as follows:

$.validator.messages.date = "hey, you entered an invalid date"

Of course, it is better to have other support for processing messages. method, which is mentioned in the description of jQuery Validation's globalization and localization.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn