分享

Jquery 轻量级的form表单校验插件,happy.js!

 看见就非常 2015-04-01

在对web开发的时候,经常需要使用到form表单,自然也就少不了form表单的js校验!这里,向大家推荐一个轻量级的form表单校验插件,happy.js!

之所以比较喜欢happy.js,主要原因有两个:
①轻量级,核心文件happy.js总共也不到200行,而且可读性也较强,通过阅读核心文件,我们可以更加轻松的了解happy.js的工作原理,从而更加灵活的使用happy.js!
注意:其他的插件功能如form valiads等插件,虽然功能很强大,但是,我们通常不大容易阅读完它的代码,掌握它的工作原理,最终只是沦为简单的插件使用者,这并不利于我们成长!
②可拓展,虽然happy.js轻量级,但是它却提供了很好的拓展性,将更多的功能的实现,依赖于开发者本身!

废话不多说,这里就介绍一下happy.js的用法吧!
A、引入happy.js的核心文件
引入jquery.js,很多插件都是基于jquery的,毕竟这个插件太牛逼了!
引入happy.method.js文件
引入happy.js文件

<head>
    <script type="text/javascript" src="./test/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="happy.methods.js"></script>
    <script type="text/javascript" src="happy.js"></script>
    <script type="text/javascript"  >
</head>

B、下面是html部分的代码

<body>
<div>
    <h1>hppy js 学习</h1>
    <form type='post' id="checkform" method="post">
        <p>姓  名:<input type="text" name="username"></p>
        <p>密  码:<input type="password" name="password"></p>
        <p>密码确认:<input type="password" name="repassword"></p>
        <p>邮  箱: <input type="text" name="email"></p>
        <p>手机号码: <input type="text" name="phone"></p>
        <p><input type="submit" value="提交"></p>
    </form>
</div>
</body>

c、下面是我们程序员,需要写的js代码:

<script type='text/javascript' language='javascript'>
    $(document).ready(function(){
        $('#checkform').isHappy({
            fields:{
                /*选中名字字段,设置校验规则,以下同理*/
                'input[name="username"]':{
                    //是否是必填的
                    required:true,
                    message:'请填写您的名字!',
                    //是否过滤
                    trim:true
                },
                'input[name="password"]':{
                    required:true,
                    message:'请填写密码!',
                },
                'input[name="repassword"]':{
                    required:true,
                    message:'两次密码输入不一致!',
                    arg:$('input[name="password"]').val(),
                    test:function(repassword, password){

                        /*但是这里很奇怪,我们并没有得到password的值,
                        这里只能再次获得一次,这里奇怪,希望有明白的朋友提供宝贵意见*/

                        var password = $('input[name="password"]').val();
                        if(password != repassword) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                },
                'input[name="email"]':{
                    required:true,
                    message:'请填写您的邮箱!',
                    //这个是在happy.method.js中定义的,而我们直接使用function没有什么区别
                    test:happy.email
                },
                'input[name="phone"]':{
                    required:true,
                    message:'请填写您的手机号!',
                    test:happy.USPhone
                }                                     
            },
            happy:function(){
                //提交成功后的回调函数
                alert('submit success');
            },
            unHappy:function(){
                //提交失败后的回调函数,
                //alert('submit failed');
            },
            errorTemplate:function(error){
                //error是一个json对象,他结果如下

                /*{messge:'显示的错误信息',
                   id:当前选择器的第一个字符+'_unhappy'}
                 */
                return $('<span style="color:red;font-weight:bold" role="alert">' + error.message + '</span>');
            }
        })        
    })
    </script>

d、ishappy方法中,所传的参数是一个json对象!
下面我们介绍一下该对象的顶级属性:
由于英文太过经典,这里就直接照搬下来了:
fields (object, see below): The configs for each field with the jquery selector as the key.
大概意思就是说:fileds是一个json对象,对象中的key是以jquery的选择器字符串作为json对象的key,可以参考上面的例子

submitButton (string): If you pass jQuery selector to this the form will be validated when that item is clicked instead of on submit.
大概意思是说:submitButton是一个jquery选择器的字符串,当单机这个按钮的时候,就会进行form表单的校验!

happy (function): A callback that gets triggered when form submission is attempted and all fields pass validation.
大概意思是说:happy是一个函数,当form表单校验成功的时候,进行的回调函数

unHappy (function): A callback that gets triggered when form submission is attempted but any fields fail validation.
大概意思是说:unHappy是一个函数,当form表单校验失败的时候进行的回调函数

errorTemplate (function): Used to generate custom error html instead of the default. Is passed a standard error object as its only parameter (which has id and message attributes). Should return the error message html.
大概意思是说:errorTemplate是一个回调函数,使用一个自定义的html错误来代替默认的,
该函数只有一个参数,这个参数就是一个错误对象,返回的是错误的html信息!可以看上面的例子!

e、filed也是一个json对象
required (boolean or 'sometimes'): You can specify that a field is required here, OR... better yet specify it with the HTML5 required attribute like so: <input type="text" required>. Happy.js will detect that too, even in IE6. So either way is fine. Also, you can pass the string 'sometimes', to specify that you always want it to run the test function to determine validity. Otherwise 'Happy' will only validate non-blank values. Passing 'sometimes' lets you make fields conditionally required.
大概意思是说:required是一个布尔类型,true表示必填,false表示非必选!或者,我们也可以使用somtimes字段,表示非必选!

message (string): Message shown in case of an error for this field.
大概意思:message是一个字符串,表单字段错误的话,就会显示这个字符串

test (function): A function that takes the field value as the first argument and returns true or false.
大概意思:test是一个函数,我们可以使用test所指的函数对该字段的值进行校验,这个函数有两个参数,第一个参数,就是当前字段的值!第二字段是我们通过arg定义的值
无论required无论是是什么,只要定义了test,都会得到执行

arg (anything): An optional second argument that will get passed to the test function. This is useful for comparing with another paramter or whatnot. If this is a function it will be evaluated. This way you can compare it to something that is evaluated at runtime such as what they put in another field or to make a server call to check if a username is available, etc.
大概意思:arg可以是任何一种类型,定义该参数后就会作为test函数的第二参数!可以看例子

trim (boolean, default: true): Password fields are not trimmed, but other field values are trimmed by default. Also, please note that if you pass a clean method it is assumed that you'll handle any trimming, etc, so the value won't be trimmed in that case.
大概意思:trim是布尔类型,表示是否对字段进行trim,true表示确定过滤,false表示不过滤!
不过无论怎么设置都不会对password进行过滤!

由于水平有限,其中还有一些问题,希望提出宝贵的意见!

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多