Declaring jQuery Validate plugin rules — attribute vs. class vs. code

前端 未结 4 1715
眼角桃花
眼角桃花 2020-12-09 15:45

In the examples for the jQuery Validate plugin, I see three different approaches to declaring validation rules:

  • CSS Classes -- e.g.
相关标签:
4条回答
  • 2020-12-09 16:13

    In answer to your specific questions:

    "How would you use the "max( value )" method with a tag attribute"

    <input id="mytext" name="mytext" max="2"/>
    

    "How would you use the "max( value )" method with a ... CSS class"

    You can't do this, use one of the other ways to setup the rule.

    0 讨论(0)
  • 2020-12-09 16:20

    you can use data-rule-required attribute , please don`t use jquery.metadata.js , i have test in jQuery Validation Plugin 1.11.1

    0 讨论(0)
  • 2020-12-09 16:30

    From the documentation http://jqueryvalidation.org/rules:

    There are several ways to specify validation rules.

    • Validation methods without parameters can be specified as classes on the element (recommended)
    • Validation methods with parameters can be specified as attributes (recommended)
    • Both can be specified as metadata using the metadata plugin [[[note that this is deprecated, so the docs appear to be out of date a bit]]]
    • Both can be specified using the rules-option of the validate()-method

    https://stackoverflow.com/a/14380401/749227 has some additional useful information.

    I prefer using the 'required' attribute over a class, though. I don't find this sort of native attribute support it directly referenced in the documentation, but since it seems like screen-readers would find it more useful than class="required" I go with that in this one case.

    As an aside, I'd love to see what other native attributes are respected by the plugin. And info on which of them are picked up by ADTs.

    0 讨论(0)
  • 2020-12-09 16:31

    You can apply rules trough data-rule attributes. This is the easiest way and possibly the best way to maintain a clean code...

    Example:

    <form id="myform">
        <input type="text" name="email" data-rule-required="true" data-rule-email="true">    
        <input type="text" name="password" id="password" data-rule-required="true" data-rule-minlength="6">
        <input type="text" name="password-confirm" data-rule-required="true" data-rule-minlength="6" data-rule-equalto="#password">
    </form>
    

    You can even provide messages through data attributes:

    <input id="cemail" name="email" data-rule-required="true" data-rule-email="true" data-msg-email="Please enter a valid email address" />
    

    In JavaScript just call:

    $('#myform').validate();
    
    0 讨论(0)
提交回复
热议问题