本人的重点是怎么构建一个简单有效可扩展的jQuery表单验证插件,这篇文章没有教你怎么用 validate plugin。我们的重点在学习一些jQuery,Javascript面向对象编程的知识。

下面是一个完整的html页面代码,可以直接运行测试的。

<html>

<head>
<title>jQuery用面向对象的思想来编写验证表单的插件</title>

<style type="text/css">

form {margin:2em 0;}
input {font-family:sans-serif; font-size:1.4em; padding:4px;}
label {display: block; margin-bottom:2px; font-size:1.4em;}
fieldset input {width: 225px; margin-bottom: 5px;}
legend {font-weight:bold; font-size:1.4em;}
fieldset { padding:2em; border: 1px solid #ccc;}
input[type=submit] {margin-top:0.5em;}

.error input {border:1px solid red;}
.errorlist {margin:0; color: red; margin-bottom:10px;}

#valid-form {margin:5px 0; display: block; color:green;}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

<script type="text/javascript">

(function($) {
    /*
    Validation Singleton
    */
    var Validation = function() {
        
        var rules = {
            
            email : {
               check: function(value) {
                   
                   if(value)
                       return testPattern(value,"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])");
                   return true;
               },
               msg : "Enter a valid e-mail address."
            },
            url : {

check : function(value) {

if(value)
                       return testPattern(value,"^https?://(.+\.)+.{2,4}(/.*)?$");
                   return true;
               },
               msg : "Enter a valid URL."
            },
            required : {
                
               check: function(value) {

if(value)
                       return true;
                   else
                       return false;
               },
               msg : "This field is required."
            }
        }
        var testPattern = function(value, pattern) {

var regExp = new RegExp(pattern,"");
            return regExp.test(value);
        }
        return {
            
            addRule : function(name, rule) {

rules[name] = rule;
            },
            getRule : function(name) {

return rules[name];
            }
        }
    }
    
    /* 
    Form factory 
    */
    var Form = function(form) {
        
        var fields = [];
    
        form.find("[validation]").each(function() {
            var field = $(this);
            if(field.attr('validation') !== undefined) {
                fields.push(new Field(field));
            }
        });
        this.fields = fields;
    }
    Form.prototype = {
        validate : function() {

for(field in this.fields) {
                
                this.fields[field].validate();
            }
        },
        isValid : function() {
            
            for(field in this.fields) {
                
                if(!this.fields[field].valid) {
            
                    this.fields[field].field.focus();
                    return false;
                }
            }
            return true;
        }
    }
    
    /* 
    Field factory 
    */
    var Field = function(field) {

this.field = field;
        this.valid = false;
        this.attach("change");
    }
    Field.prototype = {
        
        attach : function(event) {
        
            var obj = this;
            if(event == "change") {
                obj.field.bind("change",function() {
                    return obj.validate();
                });
            }
            if(event == "keyup") {
                obj.field.bind("keyup",function(e) {
                    return obj.validate();
                });
            }
        },
        validate : function() {
            
            var obj = this,
                field = obj.field,
                errorClass = "errorlist",
                errorlist = $(document.createElement("ul")).addClass(errorClass),
                types = field.attr("validation").split(" "),
                container = field.parent(),
                errors = []; 
            
            field.next(".errorlist").remove();
            for (var type in types) {

var rule = $.Validation.getRule(types[type]);
                if(!rule.check(field.val())) {

container.addClass("error");
                    errors.push(rule.msg);
                }
            }
            if(errors.length) {

obj.field.unbind("keyup")
                obj.attach("keyup");
                field.after(errorlist.empty());
                for(error in errors) {
                
                    errorlist.append("<li>"+ errors[error] +"</li>");        
                }
                obj.valid = false;
            } 
            else {
                errorlist.remove();
                container.removeClass("error");
                obj.valid = true;
            }
        }
    }
    
    /*
    Validation extends jQuery prototype
    */
    $.extend($.fn, {
        
        validation : function() {
            
            var validator = new Form($(this));
            $.data($(this)[0], 'validator', validator);
            
            $(this).bind("submit", function(e) {
                validator.validate();
                if(!validator.isValid()) {
                    e.preventDefault();
                }
            });
        },
        validate : function() {
            
            var validator = $.data($(this)[0], 'validator');
            validator.validate();
            return validator.isValid();
            
        }
    });
    $.Validation = new Validation();
})(jQuery);

</script>

<script>
                    
                    
$(function(){ // jQuery DOM ready function.

var myForm = $("#demo-form");

myForm.validation();

// We can check if the form is valid on
    // demand, using our validate function.
    $("#btn_submit").click(function() {

if(!myForm.validate()) {

myForm.append("<strong id='valid-form'>Form is valid!</strong>");
        }
    });
    
                    
});
 </script>
 
 
</head>
<body>
    
    <div class="wapper">
        <div class="content">
             <h2>Demo</h2><div class="article-demo">
                <form action="#demo-form" id="demo-form"> 
                    <fieldset>
                        <legend>Test fields</legend>
                        <div>
                            <label for="demo-field-1">Required field</label>
                            <input id="demo-field-1" validation="required" name="demo-field-1" type="text" />
                        </div>
                        <div>
                            <label for="demo-field-2">Email field</label>
                            <input id="demo-field-2" validation="email" name="demo-field-2" type="text" />
                        </div>
                        <div>
                            <label for="demo-field-3">URL field</label>
                            <input id="demo-field-3" validation="url" name="demo-field-3" type="text" />
                        </div>
                    </fieldset>
                    <div class="submit-area">
                        <input value="Validate!" type="submit" id="btn_submit" />
                    </div>  
                </form>
        </div>
    </div>
</body>

jQuery用面向对象的思想来编写验证表单的插件的更多相关文章

  1. ValidForm验证表单

    在做项目时,要求熟悉项目中验证表单的插件,所以学习一下validForm这个插件 http://validform.rjboy.cn/document.html#validformObject

  2. jquery.validate 使用--验证表单隐藏域

    jQuery validate很不错的一个jQuery表单验证插件.升级到了1.9版的后,发现隐藏表单域验证全部失效,特别是在jquery.ui.tabs.min.js构造的Tabs里的验证. 是因为 ...

  3. MVC4中 jquery validate 不用submit方式验证表单或单个元素

    正确引入MVC4 jquery验证的相关文件 <script src="/Scripts/jquery-1.4.4.js"></script> <sc ...

  4. 运用jQuery写的验证表单

    //运用jQuery写的验证表单 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...

  5. MVC中 jquery validate 不用submit方式验证表单或单个元素

    <script src="/Scripts/jquery-1.4.4.js"></script> <script src="/Scripts ...

  6. jquery.validate验证表单

    添加引用 <script src="/${appName}/commons/js/validate/jquery.validate.min.js"></scrip ...

  7. 第一百八十六节,jQuery,验证表单插件,Ajax 表单插件,验证和提交表单

    jQuery,验证表单插件,Ajax 表单插件,验证和提交表单 HTML <form id="reg" method="post" action=&quo ...

  8. JQuery基础原理 与实例 验证表单 省市联动 文本框判空 单选 复选 判空 下拉判空 确认密码判等

    JQuery 基础原理 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> & ...

  9. jquery.validate.js 验证表单时,在IE当中未验证就直接提交的原因

    jquery.validate.js 验证表单时,在IE当中未验证就直接提交的原因 今天利用了jquery.validate.js来验证表单,发现在火狐.谷歌浏览器当中都可以进行验证,但是在IE系列浏 ...

随机推荐

  1. 【BZOJ 3470】3470: Freda’s Walk 期望

    3470: Freda’s Walk Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 42  Solved: 22 Description 雨后的Poet ...

  2. [BZOJ5292][BJOI2018]治疗之雨(概率DP+高斯消元)

    https://blog.csdn.net/xyz32768/article/details/83217209 不难找到DP方程与辅助DP方程,发现DP方程具有后效性,于是高斯消元即可. 但朴素消元显 ...

  3. Beego 和 Bee 的开发实例

    Beego不是一般的web开发包.它构建在大量已存在的Go之上,提供了许多的功能,以下是提供的功能: 一个完整的ORM 缓存 支持session 国际化(i18n) 实时监测和重载 发布支持 ==== ...

  4. 【漏洞预警】方程式又一波大规模 0day 攻击泄漏,微软这次要血崩

    一大早起床是不是觉得阳光明媚岁月静好?然而网络空间刚刚诞生了一波核弹级爆炸!Shadow Brokers再次泄露出一份震惊世界的机密文档,其中包含了多个精美的 Windows 远程漏洞利用工具,可以覆 ...

  5. bzoj 3252: 攻略 -- 长链剖分+贪心

    3252: 攻略 Time Limit: 10 Sec  Memory Limit: 128 MB Description 题目简述:树版[k取方格数]   众所周知,桂木桂马是攻略之神,开启攻略之神 ...

  6. Elasticsearch基础分布式架构

    写在前面的话:读书破万卷,编码如有神-------------------------------------------------------------------- 参考内容: <Ela ...

  7. Spring_Task初探(注解,XML配置)

    这几天想写一个动态添加任务项目找了找Spring下的自带定时功能发现还真有,然后网上找了找资料写了个demo 写了两种方式来执行定时的任务(XML配置和注解) 先建两个普通的任务类(XML配置调用的任 ...

  8. Linux下以特定用户运行命令

    方法汇总: 1.su 2.sudo 3.runuser 比较常用的方式:su 示例:su - root -s /bin/sh -c "/usr/local/nginx/sbin/nginx& ...

  9. MySQLAdmin的用法

    mysqladmin 适合于linux和windows系统 linux下:mysqladmin -u[username] -p[password] status windows下:先在安装目录找到my ...

  10. mysqld --debug=d:t:i:O:n --user=mysql (源码调试)

    --debug=d:t--debug=d:f,main,subr1:F:L:t,20--debug=d,input,output,files:n--debug=d:t:i:O,\\mysqld.tra ...