Home > Web Front-end > JS Tutorial > jquery plug-in production form verification implementation code_jquery

jquery plug-in production form verification implementation code_jquery

WBOY
Release: 2016-05-16 17:50:53
Original
1109 people have browsed it

先下页面代码:

复制代码 代码如下:













a simple form


























我们定义了一个form,定义了几个输入框,请注意class属性,有的是class="required",说明该项是必填项;class="required email"说明该项是必填项,并且需要符合email格式。没有定义class的输入框不做验证。下面来看插件代码:
复制代码 代码如下:

(function ($) {
$.fn.formCheck = function (options) {
var defaults = {
errorClass: 'error'
};
var options = $.extend(defaults, options);
return this.each(function () {
var form = $(this);
//如果不是from表单,直接返回不做任何操作
if (!form.is('form')) {
return;
}
//只有当form表单提交的时候,我们才做验证
form.submit(function () {
var errorFlag = false;
//获取表单里面所有的input控件,逐一进行处理
$(':input', this).each(function (index, item) {
//获取当前对象
var element = $(item);
//移除样式
element.removeClass(options.errorClass);
//必填项验证,value值不能为空
if (element.hasClass('required') && element.val().length == 0) {
errorFlag = true;
element.addClass(options.errorClass);
}
//数字验证
if (element.hasClass('number') && element.val().length > 0 && !/^d $/.test(element.val())) {
errorFlag = true;
element.addClass(options.errorClass);
}
//email验证
if (element.hasClass('email') && element.val().length > 0
                && !/^[a-zA-Z0-9._-] @[a-zA-Z0-9.-] .[a-zA-Z]{2,4}$/.test(element.val())) {
errorFlag = true;
element.addClass(options.errorClass);
}
//验证数字长度
var num = this.className.match(/min(d )/i);
if (num && element.val().length < num[1]) {
errorFlag = true;
element.addClass(options.errorClass);
}
});
return !errorFlag;
});
});
};
})(jQuery);

demo下载地址:jQuery.plugin.formcheck
今天的课程就到此为止了。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template