JQuery 表单校验插件 validate 实践纪录

2020-12-02 11:02

阅读:564

标签:style   blog   http   java   color   使用   

JS诞生其中一个目的就是将, 服务器端的校验在客户端提前完成, 以避免用户提交数据后, 后台校验报错的糟糕用户体验。

基于JQuery库的有很多优秀的插件, 其中对于浏览器端表单进行验证的基本功能也有插件对应, validate插件便是一个。

官网地址 : http://jqueryvalidation.org/

官网文档:http://jqueryvalidation.org/documentation/

 

下面网址是开发者提供的demo, 代码可下载, 可以给大家提供参考:

http://jquery.bassistance.de/validate/demo/index.html

 

本文要介绍validate插件使用方法, 与特殊功能

校验规则设置

以 required规则为例子说明,有以下两个方法, 属性|css+valdate接口   或者  validate 接口设置规则参数。

相比方法1,方法2代码更加集中,逻辑清晰,方便维护。

 

  方法1,添加required属性, 

    p>
      label for="ccomment">Your comment (required)label>
      textarea id="ccomment" name="comment" required>textarea>
    p>

或者 添加 required 到class中

    p>
      label for="ccomment">Your comment (required)label>
      textarea id="ccomment" name="comment"class=“required”>textarea>
    p>

然后找到form DOM调用validate接口,完成表单规则设置动作:

$("#commentForm").validate();

  方法2, 直接使用validate接口设置规则:

mamicode.com,搜素材
$(".selector").validate({
  rules: {
    // simple rule, converted to {required:true}
    name: "required",
    // compound rule
    email: {
      required: true,
      email: true
    }
  }
});
mamicode.com,搜素材

  

 错误提示区域的样式自定义

插件默认提供的错误提示是, 在校验控件的右侧给予一个 红色字符串 显示, 如果希望给错误提示语, 换个位置和添加样式, 就需要使用插件提供的接口了。

validate 提供  errorPlacement 接口, 可以定制错误提示的样式和位置。 http://jqueryvalidation.org/?s

本文给出, 将错误提示语放在报错控件下方, 并添加错误提示边框和背景色的方法:

mamicode.com,搜素材

新增validate扩展JS文件 formValidateExt.js:

mamicode.com,搜素材
mamicode.com,搜素材
$.validator.setDefaults({
    errorPlacement: function (error, element) {
        /* 生成显示错误提示HTML DOM */
        var tipHTML = "
"; var tipObj = $(tipHTML); error.appendTo(tipObj); tipObj.insertAfter(element); var offset = element.offset(); var top = offset.top + element.height(); var left = offset.left; console.log("top="+top) console.log("height="+element.height()) console.log("left="+left) tipObj.css("top", top); tipObj.css("left", left); } }); //手机号码验证 jQuery.validator.addMethod("isMobile", function(value, element) { var length = value.length; var mobile = /^(((13[0-9])|(15[0-9])|(18[0-9])|(170))\d{8})$/; return this.optional(element) || (length == 11 && mobile.test(value)); }, "请正确填写您的手机号码"); //电话号码验证 jQuery.validator.addMethod("isTel", function(value, element) { var tel = /^\d{3,4}-?\d{7,9}$/; //电话号码格式010-12345678 return this.optional(element) || (tel.test(value)); }, "请正确填写您的电话号码");
mamicode.com,搜素材

 

mamicode.com,搜素材

  新增validate扩展css文件 formValidateExt.css:

mamicode.com,搜素材
div.errorLabelWraper{
    position: absolute;
    display:inline-block;
    padding-left: 5px;
    line-height: 30px;
    border:2px solid #A9A9A9;
    background-color: #FEFEFE;
    border-radius:5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

label.error{
    color: #FF0000;
}
mamicode.com,搜素材

  HTML示例文件:

mamicode.com,搜素材
mamicode.com,搜素材
html>
head> 
    meta http-equiv="content-type" content="text/html; charset=gb2312" />
    script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">script>
    script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js">script>
    script type="text/javascript" src="../formValidateExt.js">script>
    script type="text/javascript" src="../jquery.cityselect.js">script> 
    link rel="stylesheet" type="text/css" href="../formValidateExt.css" />
head> 
body>
    form id="form1" method="post" action="">
        fieldset>
            legend>Genderlegend>
            label for="gender_male">
                input  type="radio" id="gender_male" value="m" name="genderRadio">
                Male
            label>
            label for="gender_female">
                input  type="radio" id="gender_female" value="f" name="genderRadio">
                Female
            label>
        fieldset>
        
        fieldset>
            legend>Spamlegend>
            label for="spam_email">
                input type="checkbox" class="checkbox" id="spam_email" value="email" name="spamCheckbox">
                Spam via E-Mail
            label>
            label for="spam_phone">
                input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spamCheckbox">
                Spam via Phone
            label>
            label for="spam_mail">
                input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spamCheckbox">
                Spam via Mail
            label>
        fieldset>
        
        p>
            label for="jungleSelect">Please select a jungleSelect nounlabel>br>
            select id="jungleSelect" name="jungleSelect">
                option value="">option>
                option value="1">Bugaoption>
                option value="2">Bagaoption>
                option value="3">Oioption>
            select>
        p>
        
        p>
            label for="phoneNum">phoneNumlabel>
            input id="phoneNum" name="phoneNum" type="text" />
        p>
    
        div id="city"> address
            select class="prov" name="prov" >select>  
            select class="city" name="city">select> 
            
        div> 
        
        p>
            input id="submit" class="submit" type="submit" value="Submit">
        p>
    form>

    script type=‘text/javascript‘> 
        $(document).ready(function() {
            $("#city").citySelect();  
        
            $("#form1").validate({
                groups: {
                    address: "prov city"
                },
                rules: {
                    genderRadio: {
                        required: true,
                    },
                    spamCheckbox: {
                        required: true,
                    },                    
                    jungleSelect: {
                        required: true,
                    },
                    prov: {
                        required: true,
                    },
                    city: {
                        required: true,
                    },
                    phoneNum: {
                        required: true,
                        isMobile: true,
                        remote: "checkSame.php"
                    }
                },
                messages: {
                    phoneNum: {
                        remote:  $.validator.format("{0} 已经注册过。")
                    }
                }
            });
        });
        
    script>
body>
html>
mamicode.com,搜素材

 

mamicode.com,搜素材

  服务器端校验

  对于一些校验,不能够在浏览器端实现的, 例如手机号重复,姓名重复等, 需要后台检索数据库给结果的情况,

validate插件提供了 remote规则, 可以实现远程校验:例如上例中phoneNum添加的规则, “checkSame.php”是后台的校验文件路径:

?
1
remote: "checkSame.php"

下面给出 此文件后台实现, true表示校验通过, false表示不通过:

mamicode.com,搜素材
php
if($_GET)
{
    $phoneNum = $_GET[‘phoneNum‘];
    if($phoneNum == ‘123456‘)
    {
        echo ‘false‘;
    }
    else
    {
        echo ‘true‘;
    }
    exit();
}
?>
mamicode.com,搜素材

 

  

注释: 上例中, 还有一个省市联动的JQuery插件(js/jquery.cityselect.js),

 可以完成表单中选择省份和城市的功能, 见 http://www.helloweba.com/view-blog-188.html

 

 

 

 

JQuery 表单校验插件 validate 实践纪录,搜素材,soscw.com

JQuery 表单校验插件 validate 实践纪录

标签:style   blog   http   java   color   使用   

原文地址:http://www.cnblogs.com/lightsong/p/3699979.html


评论


亲,登录后才可以留言!