• jquery.validation.js 使用


    引用文件:

      "~/assets/global/plugins/jquery-validation/js/jquery.validate.min.js",
        "~/assets/global/plugins/jquery-validation/js/jquery.metadata.js",
        "~/assets/global/plugins/jquery-validation/js/localization/messages_cn.js",

    jquery.metadata.js

    /*
     * Metadata - jQuery plugin for parsing metadata from elements
     *
     * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
     *
     * Dual licensed under the MIT and GPL licenses:
     *   http://www.opensource.org/licenses/mit-license.php
     *   http://www.gnu.org/licenses/gpl.html
     *
     * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $
     *
     */
    
    /**
     * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
     * in the JSON will become a property of the element itself.
     *
     * There are three supported types of metadata storage:
     *
     *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
     *          
     *   class: Inside the class attribute, wrapped in curly braces: { }
     *   
     *   elem:  Inside a child element (e.g. a script tag). The
     *          name parameter indicates *which* element.
     *          
     * The metadata for an element is loaded the first time the element is accessed via jQuery.
     *
     * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
     * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
     * 
     * @name $.metadata.setType
     *
     * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
     * @before $.metadata.setType("class")
     * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
     * @desc Reads metadata from the class attribute
     * 
     * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
     * @before $.metadata.setType("attr", "data")
     * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
     * @desc Reads metadata from a "data" attribute
     * 
     * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
     * @before $.metadata.setType("elem", "script")
     * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
     * @desc Reads metadata from a nested script element
     * 
     * @param String type The encoding type
     * @param String name The name of the attribute to be used to get metadata (optional)
     * @cat Plugins/Metadata
     * @descr Sets the type of encoding to be used when loading metadata for the first time
     * @type undefined
     * @see metadata()
     */
    
    (function($) {
    
    $.extend({
        metadata : {
            defaults : {
                type: 'class',
                name: 'metadata',
                cre: /({.*})/,
                single: 'metadata'
            },
            setType: function( type, name ){
                this.defaults.type = type;
                this.defaults.name = name;
            },
            get: function( elem, opts ){
                var settings = $.extend({},this.defaults,opts);
                // check for empty string in single property
                if ( !settings.single.length ) settings.single = 'metadata';
                
                var data = $.data(elem, settings.single);
                // returned cached data if it already exists
                if ( data ) return data;
                
                data = "{}";
                
                if ( settings.type == "class" ) {
                    var m = settings.cre.exec( elem.className );
                    if ( m )
                        data = m[1];
                } else if ( settings.type == "elem" ) {
                    if( !elem.getElementsByTagName )
                        return undefined;
                    var e = elem.getElementsByTagName(settings.name);
                    if ( e.length )
                        data = $.trim(e[0].innerHTML);
                } else if ( elem.getAttribute != undefined ) {
                    var attr = elem.getAttribute( settings.name );
                    if ( attr )
                        data = attr;
                }
                
                if ( data.indexOf( '{' ) <0 )
                data = "{" + data + "}";
                
                data = eval("(" + data + ")");
                
                $.data( elem, settings.single, data );
                return data;
            }
        }
    });
    
    /**
     * Returns the metadata object for the first member of the jQuery object.
     *
     * @name metadata
     * @descr Returns element's metadata object
     * @param Object opts An object contianing settings to override the defaults
     * @type jQuery
     * @cat Plugins/Metadata
     */
    $.fn.metadata = function( opts ){
        return $.metadata.get( this[0], opts );
    };
    $.validator.setDefaults({
        debug: true,
        errorPlacement: function (error, element) {
            var p = $("<p class='errmsg'>");
            p.append(error);
            p.appendTo(element.parent());
        }
    })
    })(jQuery);
    View Code

    messages_cn.js

    (function (factory) {
        if (typeof define === "function" && define.amd) {
            define(["jquery", "../jquery.validate"], factory);
        } else {
            factory(jQuery);
        }
    }(function ($) {
    
        $.extend($.validator.messages, {
            required: "必填",
            remote: "请修正该字段",
            email: "请输入正确格式的电子邮件",
            url: "请输入合法的网址",
            date: "请输入合法的日期",
            dateISO: "请输入合法的日期 (ISO).",
            number: "请输入合法的数字",
            digits: "只能输入整数",
            creditcard: "请输入合法的信用卡号",
            equalTo: "请再次输入相同的值",
            accept: "请输入拥有合法后缀名的字符串",
            maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串"),
            minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"),
            rangelength: $.validator.format("请输入一个长度介于 {0} 和 {1} 之间的字符串"),
            range: $.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
            max: $.validator.format("请输入一个最大为 {0} 的值"),
            min: $.validator.format("请输入一个最小为 {0} 的值")
        });
    
    }));
    View Code

    有一些公用的写在了metadata.js里面

    $.validator.setDefaults({
        debug: true,
        errorPlacement: function (error, element) {
            var p = $("<p class='errmsg'>");
            p.append(error);
            p.appendTo(element.parent());
        }
    })
    <style type="text/css">
            .errmsg {
                margin: -30px -40px 0 0px;
                float: right;
                color: #F30;
            }
        </style>

    就是显示错误信息位置设定

    使用:

    1.建表单form,

    2.把控件name赋值(只要各不相同即可),并在class里面赋值,比如required

    3.在最后时判断是否验证通过再进行下一步操作

      if ($("#formFinance").valid()) {
                        if (!financeFlag) {
                            financeFlag = true;
                            o = self.selectFinanceItem();

    上面的是早期的jquery.validate.js,我测的是1.5.5版本

    最新的1.13版本的使用方法发生了变动,不需要jquery.metadata.js文件

    <form id="registerForm" method="get" action="">
      <fieldset>
        <p>
          <label for="cusername">用户名</label>
          <input id="cusername" name="username" type="text" data-rule-required="true" data-rule-rangelength="[2,10]" data-msg-required="用户名不能为空" data-msg-rangelength="用户名长度必须是2到10个字符">
        </p>
        <p>
          <label for="cpassword">密码</label>
          <input id="cpassword" name="password" type="password" data-rule-required="true" data-rule-minlength="6" data-msg-required="密码不能为空" data-msg-minlength="至少设置6位密码">
        </p>
        <p>
          <label for="cconfirmpassword">确认密码</label>
          <input id="cconfirmpassword" name="confirmpassword" type="password" data-rule-equalTo="#cpassword" data-msg-equalTo="两次密码不一致">
        </p>
        <p>
          <label for="cemail">邮箱</label>
          <input id="cemail" name="email" data-rule-required="true" data-rule-email="true" data-msg-required="邮箱不能为空" data-msg-email="邮箱的格式不正确">
          </input>
        </p>
        <p>
          <label for="chasreferee">有推荐人请勾选</label>
          <input type="checkbox" id="chasreferee" name="hasreferee">
        </p>
        <p>
          <label for="creferee">推荐人</label>
          <input id="creferee" name="referee" data-rule-required="#chasreferee:checked" data-msg-required="推荐人不能为空">
          </input>
        </p>
        <p>
          <input type="submit" value="提交">
        </p>
      </fieldset>
    </form>

    直接data-属性使用

    也可以自己手动设置具体信息:

      $("#formFinance").validate({
                        rules: {
                            fFinanceName: { required: true },
                            fLoanCount: { required: true ,min:0}
                        },
                        messages: {
                            fFinanceName: {
                                required: "必填",
                            },
                            fLoanCount: {
                                required: "必填",
                            },
                            fRate: {
                                required: "必填",
                            },
                            fFee: {
                                required: "必填",
                            },
                            fPeriod: {
                                required: "必选",
                            } 
                        },
                        errorPlacement: function (error, element) {
                            var p = $("<p class='errmsg'>");
                            p.append(error);
                            p.appendTo(element.parent());
                        }
                    });

    http://blog.csdn.net/hliq5399/article/details/6557789

    http://www.cnblogs.com/linjiqin/p/3431835.html

    http://www.runoob.com/jquery/jquery-plugin-validate.html

    http://www.cnblogs.com/yanjunwu/p/3764740.html

     https://github.com/ffmike/jquery-validate

  • 相关阅读:
    !JS实战之随机像素图
    bgp选路原则【第二部】
    BGP基础【第三部】
    【★】KMP算法完整教程
    ★如何引导客户需求?几个经…
    html标签缺省(自带)样式大全
    Web颜色对照表大全
    PS各个工具的字母快捷键和英…
    色相、明度及饱和度
    用webgl打造自己的3D迷宫游戏
  • 原文地址:https://www.cnblogs.com/hongdada/p/4864669.html
Copyright © 2020-2023  润新知