论坛首页 Web前端技术论坛

真正简单的基于prototype的表单验证

浏览 4115 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-03-20  
由 searchadmin 于 周二, 10/16/2007 - 06:44 提交。
真正简单的基于prototype的表单验证
tag:prototype 数据验证 表单验证 validator js javascript
Really easy field validation
官方地址:http://tetlaw.id.au/view/javascript/really-easy-field-validation
Here's a form validation script that is very easy to use.
Current Version: 1.5.4.1 - 06 Jan 2007 - Demo / Download

真正简单的表单验证
在这里我们提供一个使表单验证不再头疼的一个验证脚本
当前版本:1.5.4.1-06 Jan 2007 - 演示/下载

Instructions

The basic method is to attach to the form's onsubmit event, read out all the form elements' classes and perform validation if required. If a field fails validation, reveal field validation advice and prevent the form from submitting.

Include the javascript libraries:

用法说明:
使用的基本方法是绑定到表单的onsubmit事件,从所有表单项的class中读取相应的规则并且做验证,如果表单中的某一项验证失败,将会显示我们自定义的帮助信息并且阻止表单提交。
网页包含两个javascript的脚本库:





You write elements like this:
你可以按照下面的html格式书写你的表单:



passing the validation requirements in the class attribute.

You then activate validation by passing the form or form's id attribute like this:

通过在表单项的class属性中添加requirements验证,我们就可以像下面这样通过指定表单的id来激活验证:



new Validation('form-id'); // OR new Validation(document.forms[0]);


It has a number of tests built-in but is extensible to include your custom validation checks.
The validator also avoids validating fields that are hidden or children of elements hidden by the CSS property display:none. This way you can give a field the class of 'required' but it's only validated if it is visible on the form. The demo illustrates what I am talking about

有很多内置的表单验证项并且我们可以对客户端的验证进行扩展,该验证应尽量避免被设置为hidden的表单项和被添加在display被设为none层中的表单。这种方式你可以设置一个表单的class为'required',但是他尽在表单上可视的元素起作用。演示文档说明了这一点。


Options

Here's the list of classes available to add to your field elements:
选项:
这里给出了表单验证器内置的验证规则
* required (not blank)
--表单项不能为空
* validate-number (a valid number)
--验证数字
* validate-digits (digits only)
--验证两位数
* validate-alpha (letters only)
--验证字母
* validate-alphanum (only letters and numbers)
--验证字母或数字
* validate-date (a valid date value)
--验证日期
* validate-email (a valid email address)
--验证email邮件地址
* validate-url (a valid URL)
--验证网址格式
* validate-date-au (a date formatted as; dd/mm/yyyy)
--验证dd/mm/yyyy格式的日期
* validate-currency-dollar (a valid dollar value)
* validate-selection (first option e.g. 'Select one...' is not selected option)
* validate-one-required (At least one textbox/radio element must be selected in a group - see below*)
*To use the validate-one-required validator you must first add the class name to only one checkbox/radio button in the group (last one is probably best) and then place all the input elements within a parent element, for example a div element. That way the library can find all the checkboxes/radio buttons to check and place the validation advice element at the bottom of the parent element to make it appear after the group of checkboxes/radio buttons.

使用validate-one-required验证规则,你必须首先添加class项到单选按钮或者多选框组中的一个(建议在最后一个添加)然后在父级元素中放置其他的input元素,比如一个层元素。这样我们的验证库可以找到所有需要验证的多选框和单选按钮对其验证并且在容器的底部表单项的后面显示出错帮助。

When the validation object is initialised you can pass the option {stopOnFirst : true} to enable the stop on first validation failure behaiour. The demo above has this set to false which is the default. If set to true only the first validation failure advice will be displayed when the form is submitted instead of all at once.

当验证对象初始化实例的时候你可以通过设置选项{stopOnFirst:true}来使第一个验证出错的时候就不再验证后面的选项。上面的演示设置了默认选项false。如果设置为true。那么出错的时候将只显示第一个出错的信息而不是所有的出错提示。


new Validation('form-id',{stopOnFirst:true});

You can also pass the option {immediate : true} to enable field valiation when leaving each field. That is on the onblur event for all the form elements.

同样你可以设置选项{immediate : true}来使在每一表单项失去焦点时验证,同表单元素的onblur事件


By default the library will add an event listener to the form's onsubmit event and stop the event if the validation fails. If you pass the option {onSubmit : false} it wont do that. This way you can call the validate function manually within your own javascript.

默认验证器会添加一个表单的onsubmit事件监听并且阻止表单的submit事件如果表单验证失败的话。如果你添加了{onSubmit : false}选项的话,这一切将不会发生。使用这种方式就可以在form onsubmit的时候调用自定义的javascript函数

By default the library will focus on the first field that contains an error. If you pass the option {focusOnError : false} it wont do that.

默认情况下验证失败选项会自动获得输入焦点focus。通过设置选项{focusOnError : false}禁用此功能。

You can also pass the option {useTitles : true} to make the field validators use the form elements' title attribute value as the error advice message.

你也可以设置option {useTitles : true}来使用表单项的标题title属性值来用作出错提示。

You can set callbacks by using the options {onFormValidate : yourFunction, onElementValidate : yourFunction}.

可以通过选项{onFormValidate : yourFunction, onElementValidate : yourFunction}来使用自定义函数。

onFormValidate is called after form validation takes place and takes two arguments: the validation result (true or false) and a reference to the form. OnElementValidate is called after each form element is validated and also takes 2 arguments: the validation result (true or false) and a reference to the form element.

onFormValidate 在表单验证后发生并且带两个参数--表单验证结果(true or false)和 reference to the form,onElementValidate 在每一个表单项被验证后发生带两个参数--表单项验证结果(true or false)和 reference to the form element.

Instead of using the error message in the validator you can create your own validation advice page element. Now when the script is creating the advice element it first looks for an element with an id matching 'advice-' + validation-class-name + '-' + element.id and if not found then one matching 'advice-' + element.id . If your form element does not have an id attribute then match the name attribute. If it finds an element it will make that one appear. See the 'Donation' field in the demo for an example. If you make a custom validation advice element make sure you set the style to display : none .

你可以自定义验证出错信息而不使用默认通过设置表单项。现在验证器将会首先从id为'advice-' + validation-class-name + '-' + element.id 的元素如果没有则从'advice-' + element.id 匹配,如果表单元素没有id属性,将会匹配表单的name属性。如果发现元素则使其出现。演示文档中的'Donation'项说明了这个问题。使用自定义advice message 要确保显示容器的display为none;

Also if you reference the effects.js file from Scriptaculous in your page head, it'll use a fade-in effect for the validation advice.

你可以引用scriptaculous框架中的effect.js文件,来实现出错建议信息的显示特效:


CSS Hooks

As well as the validation css classes above, the validation library uses CSS classes to indicate validation status:
同上面的验证css定义。验证器使用样式表定义规则来标识验证状态。
validation-failed and validation-passed

The validation advice element has a class of validation-advice and an id matching the following pattern
验证建议信息使用validation-advice类 并且 其id格式如下:
'advice-' + validation-class-name + '-' + element.id

so if the field ' birthdate' uses the ' validate-date' validation class then the validation advice element will have an id of ' advice-validate-date-birthdate'.
因此 表单项'birthdate'使用'validate-date'验证类。那么他的建议信息容器的id应该为:'advice-validate-date-birthdate'.

Javascript API

By default the class attaches an event observer to the form's onsubmit event. If you prefer to do the form submit via javascript yourself you can still validate the form like this:

Javascript 接口

默认的验证类绑定表单的onsubmit事件。如果你打算触发自己的表单提交事件可以按以下格式书写:


var valid = new Validation('form-id', {onSubmit:false});
var result = valid.validate();

The instance method, validate(), will return true or false.

The class has an instance function which resets all the field validation:

实例函数validate()将返回true 或者 false

验证器有一个重置所有验证的方法:


var valid = new Validation('form-id');
valid.reset();

Note that it doesn't reset the form, just the validation.

The Validation class also has some static methods that can be used independantly.
要注意的是上面的reset()仅仅重置验证,而不像表单的reset一样重置表单内容
验证类还有很多可以独立调用的静态方法

Validation.validate([element OR element id] [, options])

This validates the field (or field with that id), using all validation classes present. You can also pass the option {useTitle : true} to make the field validator use the form element's title attribute value as the error advice message.

You can run a specific validation test on a field or field value by doing this:

我们可以通过前面的验证类设置表单验证,同样的 你也可以通过选项{useTitle : true}来使用表单项的title属性值作为出错信息提示.

你可以像下面这样运行一个属于某个表单项的验证测试或者对某个特定值进行测试。

Validation.get('validator-name').test(value [, element]);

To add your own validator do this:
像下面这样添加你自己的验证规则:

Validation.add('class-name', 'Error message text', function(value [, element]) {
return /* do validation here */
}, options);

or this:
或者这样:
Validation.add('class-name', 'Error message text', options);

The first example above includes a function as the third argument. The function enables you to write your own custom validation. The options argument is optional. The second example the third argument has become the options argument. Validator options can be used to perform common validation options without the need to write them into a function. Multiple options can be combined to create a complex validator and they can also enhance your custom validation function. Here are the available options and example usage below:

上面的第一个例子包含一个带三个参数的函数定义,这个函数使你可以书写自己的验证规则。参数options是可选的。第二个例子的第三个参数变成了options,验证选项可以被用来使用验证规则而不用书写第一个例子中的function。一个复合选项可以定义一组验证规则组成的验证。这样可以增强你的验证函数。下面是两个实例:

Validation.add('class-name', 'Error message text', {
pattern : new RegExp("^[a-zA-Z]+$","gi"), // only letter allowed
minLength : 6, // value must be at least 6 characters
maxLength : 13, // value must be no longer than 13 characters
min : 5, // value is not less than this number
max : 100, // value is not more than this number
notOneOf : ['password', 'PASSWORD'], // value does not equal anything in this array
oneOf : ['fish','chicken','beef'], // value must equal one of the values in this array
is : '5', // value is equal to this string
isNot : 'turnip', //value is not equal to this string
equalToField : 'password', // value is equal to the form element with this ID
notEqualToField : 'username', // value is not equal to the form element with this ID
include : ['validate-alphanum'] // also tests each validator included in this array of validator keys (there are no sanity checks so beware infinite loops!)
});

For example here's one of the in-built ones:

Validation.add('validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
return Validation.get('IsEmpty').test(v) || /^[a-zA-Z]+$/.test(v)
});

And here's a custom one using options:

Validation.addAllThese('validate-password', 'Your password must be more than 6 characters and not be 'password' or the same as your name', {
minLength : 7,
notOneOf : ['password','PASSWORD','1234567','0123456'],
notEqualToField : 'username'
});

If you supply a custom function and a combination of options they are all tested and if all are true the field validates.

When you add a new validator it is added to a static group of validation methods with the class name as key. You then must use the class in the form elements to use your custom validation function.

To make adding mupltiple custom validators easier you can use Validation.addAllThese() like this:
如果你提供一个自定义函数 和 一组选项 ,其中所有的选项均通过验证时才能通过验证。
新增一个验后你必须在表单验证中使用该验证类

Validation.addAllThese([
['required', 'This is a required field.', function(v) {
return !Validation.get('IsEmpty').test(v);
}],
['validate-number', 'Please use numbers only in this field.', function(v) {
return Validation.get('IsEmpty').test(v) || !isNaN(v);
}],
['validate-digits', 'Please use numbers only in this field.', function(v) {
return Validation.get('IsEmpty').test(v) || !/[^d]/.test(v);
}]
]);

You pass an array, where each element of the array is an array with 3 or 4 elements: [className, error, function, options] or [className, error, options]
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics