首页 > 代码库 > jQuery用面向对象的思想来编写验证表单的插件

jQuery用面向对象的思想来编写验证表单的插件

本人的重点是怎么构建一个简单有效可扩展的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="http://www.mamicode.com/Validate!" type="submit" id="btn_submit" />
                    </div>  
                </form>
        </div>
    </div>
</body>

 

jQuery用面向对象的思想来编写验证表单的插件