`
xyzroundo
  • 浏览: 509025 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类
最新评论

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

    博客分类:
  • js
阅读更多
由 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]
分享到:
评论

相关推荐

    基于Prototype的Validation表单验证插件.rar

    实现Ajax风格的无刷新表单验证功能,当用户输入完表单,即时显示该项输入是否正确,不正确则会给出提示,适合那些比较喜欢简洁风格,又要求功能准确的用户,本款表单验证插件基于Prototype插件。

    表单验证类 基于prototype的validation.js

    `validation.js`是一个专门用于前端表单验证的库,它基于Prototype JavaScript框架构建,提供了一种简单且灵活的方式来实现这一功能。 **Prototype框架** 是一个广泛使用的JavaScript库,它扩展了JavaScript语言的...

    基于prototype的表单验证框架rapid-validation-v1.0

    简洁,快速的验证语法 无需编写验证提示信息(当然也支持自定义提示信息) 错误消息在指定地方显示 支持组合验证 Ajax支持 基于prototype.js 支持国际化 易于扩展 基于标准的Html属性...

    最简单的表单验证框架发布

    综上所述,这个压缩包提供了一个基于JavaScript的表单验证框架,可能包含以下关键知识点: - HTML表单验证基础 - 使用JavaScript进行前端验证 - 如何集成和配置验证框架 - Prototype库的使用 - 多语言支持(尤其是...

    基于prototype的validation.js发布2.3.4新版本,让你彻底脱离表单验证的烦恼

    增加validate-ajax以支持ajax验证 增加validate-pattern直接通过正则表达式的认证 修改validate-equlas以验证密码与确认密码的问题 增加less-than与great-than的验证以支持开始日期与结束日期相比较的问题 增加...

    Ajax最全页面验证-基本prototype框架

    本文将深入探讨Ajax在表单验证中的应用,特别是基于Prototype框架的实现方式,以及动态验证的重要性。 一、Ajax基础 Ajax的核心是通过JavaScript与服务器进行异步通信,无需刷新整个页面就能获取或更新数据。它由...

    ASP基于Prototype的Ajax无刷新登录实例

    ASP基于Prototype的Ajax无刷新登录实例是一个非常适合初学者学习AJAX技术的应用案例。在这个实例中,我们将探讨如何在ASP(Active Server Pages)环境中利用Prototype JavaScript库实现无刷新的用户登录功能,同时...

    javascript表单验证类

    在表单验证类中,我们可以利用Prototype扩展验证规则,例如: ```javascript FormValidator.prototype.isRequired = function(field) { return field.value.trim() !== ''; }; // 使用 formValidator.isRequired...

    ASP源码—基于Prototype的Ajax无刷新登录实例.zip

    ASP源码—基于Prototype的Ajax无刷新登录实例.zip是一个压缩包,其中包含了使用ASP(Active Server Pages)技术构建的一个无刷新登录系统。该系统利用了Ajax(Asynchronous JavaScript and XML)技术,通过...

    ASP实例开发源码—ASP基于Prototype的Ajax无刷新登录实例.zip

    这个实例“ASP基于Prototype的Ajax无刷新登录实例”是关于如何在ASP中利用Ajax技术实现用户登录功能,无需页面刷新即可完成交互。Ajax(Asynchronous JavaScript and XML)是一种在不重新加载整个网页的情况下更新...

    javascript验证框架

    在本主题中,我们将深入探讨基于Prototype的JavaScript验证框架。 Prototype是一个广泛使用的JavaScript库,它扩展了JavaScript的内置对象,并提供了许多实用的功能,包括DOM操作、Ajax交互以及对象创建等。当...

    Javascript表单验证控件(Validator v1.05).rar

    Javascript表单验证控件(Validator v1.05).rar --------------------------------- 内含以下两个文件: Validator.chm(详细的使用帮助文档) validator.js(源代码,当然没有prototype.js强大,但最...

    超好用的表单验证插件(LiveValidation)

    它有standalone version 和基于prototype的prototype.js version两个版本,可能是作者喜欢用prototype吧,呵呵。 livevalidation 官方网站(英文):http://livevalidation.com/examples LiveValidation 官方文档...

    jsvalidation_脚本实例_

    "jsvalidation_脚本实例_" 涉及到的是一个基于Prototype库的表单验证插件。Prototype是一个强大的JavaScript库,它为JavaScript开发提供了许多便利的功能,包括DOM操作、事件处理以及对象和类的扩展。 1. **...

    Really easy field validation with Prototype 1.5.3 中文扩展版

    "Really easy field validation with Prototype 1.5.3 中文扩展版"是一个针对Prototype JavaScript库的前端验证插件,旨在简化网页表单的数据验证过程。这个工具以其简单易用和强大的功能著称,并且提供了对多语言的...

    prototype整合json实现无刷新验证用户名

    在Web开发中,为了提供更好的用户体验,我们常常需要实现无刷新验证功能,即在用户输入信息时即时检查数据的有效性,而无需提交整个表单。本教程将关注如何使用JavaScript库Prototype结合JSON(JavaScript Object ...

    vue elementui form表单验证的实现

    表单验证是任何Web应用中不可或缺的功能,它保证了用户提交的数据是符合预期格式的。本文将详细介绍如何在Vue项目中使用Element UI来实现表单验证。 Element UI提供了丰富的表单组件,例如 `<el-form>`、`...

    介绍ajax开发框架的书《Prototype and Scriptaculous quickly》

    - **表单验证**:利用Prototype的DOM操作能力,可以轻松实现客户端表单验证。 - **动态内容加载**:通过Ajax技术,可以在不刷新整个页面的情况下加载新的内容。 - **交互式元素**:例如弹出窗口、拖拽功能等,都可以...

Global site tag (gtag.js) - Google Analytics