问题
I'm looking into using the html5 data- attributes to pass the validation rules to jquery.validate as a stop gap until the plugin is updated with HTML5 support. I'm using jquery 1.4.2, jquery.validate 1.7 and jquery.validate 2.1. In my HTML I'm using code such as this:
<input name="foo" type="text" data-validate="{required:true,digits:true}" />
In my jQuery I'm doing the following:
<script type="text/javascript">
$.metadata.setType ("html5");
$(function ()
{
$('#myForm').validate ({debug:true});
});
</script>
This just causes an error message, validator.methods[method] is undefined
I did do a metadata() on the element with the data-validate attribute, and I got an object returned named validate with my attributes set in it, so I know metadata is finding the attribute and loading from it, but the validate plugin can't seem to handle it. If I go back to class="{validate:{...}}" and comment out the line that configures metadata to use HTML 5, it all works as it should.
Am I doing something wrong, or is there an issue with the validate and/or metadata plugins?
回答1:
Try:
$.metadata.setType("html5");
$('#myForm').validate({
meta: "validate"
});
http://jsfiddle.net/petersendidit/5YND2/
回答2:
In case anyone runs across this using a newer version of jQuery, jQuery Validate and the jQuery metadata plugin, all of the documentation I have found for using these together is out of date. While the jQuery Validate plugin can still make use of jQuery Metadata, the newer versions of jQuery Metadata don't support "html5" as a type anymore because jQuery now natively supports HTML5 data- attributes as a source of metadata. However, jQuery Validate has not been updated to use this.
The solution for this (at least until jQuery Validate is updated to support the built-in support for metadata using data- attributes is to use the 'attr' type and point directly to your data- attribute. For instance:
$.metadata.setType("attr", "data-validate");
$("form").validate();
Notice there is no need to pass the "meta" tag because the metadata library is directly going to the correct attribute to read the values. Here is a modified jsFiddle using updated versions of all of the libraries:
http://jsfiddle.net/Wcu4L/
来源:https://stackoverflow.com/questions/4105959/jquery-validate-jquery-metadata-and-html5-data