声明jQuery Validate插件规则-属性与类与代码 [英] Declaring jQuery Validate plugin rules -- attribute vs. class vs. code

查看:73
本文介绍了声明jQuery Validate插件规则-属性与类与代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery Validate插件的示例中,我看到了三种声明验证规则的方法:

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

  • CSS类-例如<input type="text" name="whatever" class="required" />
  • 属性-例如<input type="text" name="whatever" required />
  • JS代码-例如$("#myForm").validate({ rules: { whatever: "required", ... } });
  • CSS Classes -- e.g. <input type="text" name="whatever" class="required" />
  • Attributes -- e.g. <input type="text" name="whatever" required />
  • JS code -- e.g. $("#myForm").validate({ rules: { whatever: "required", ... } });

但是我在文档中看不到任何解释您为什么要在一个之上使用一个的解释.我也没有看到关于每种方法如何使用验证方法的解释(例如,如何您将"max(value)"方法与tag属性或CSS类一起使用?).

But I don't see anywhere in the docs that explains why you'd use one over the other. Nor do I see an explanation of how to use the validation methods with each approach (for example, how would you use the "max( value )" method with a tag attribute or a css class?).

这三种方法之间的权衡是什么?以及您如何精确地使用每种方法声明所有不同的验证方法?

What are the tradeoffs between these three approaches? And how exactly do you declare all the different validation methods using each approach?

推荐答案

您可以通过数据规则属性应用规则.这是保持干净代码的最简单方法,也可能是最好的方法.

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

示例:

<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" />

在JavaScript中只需调用:

In JavaScript just call:

$('#myform').validate();

这篇关于声明jQuery Validate插件规则-属性与类与代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆