js原生态表单验证Validator类

功能点:

1.原生js,不依赖任何库
2.动态添加验证规则
3.设置是否实时报错
4.错误提示的样式,单条显示还是合并显示,以及函数形式
5.遇到错误是否停止接下来的验证
6.常用验证,邮箱,字符串,手机,以及两个字段进行比较的验证,支持自定义正则
7.单条验证规则失败后的提示信息,支持字符串或者函数

使用说明:

 代码如下 复制代码

var F = Validator('form表单name值',{
        together : false, //默认遇错误打断,显示单条错误信息,默认为false(只显示一条)
        errShow : 'alert', //错误提示,默认为alert,支持字符串(alert,single,multiple),自定义function(string || array())
        errBox : 'error_strings', //错误消息class,默认为form表单中的 .error_strings
        errPar : 'li', //单个表单元素的父级元素,用于定位错误的位置 li > (span > input ) ~ span.error_strings
        timely : false //实时判断,是否失去焦点以及change判断
});

//添加验证规则,传参为二位数组

F.addRule([
    ["username","required",'姓名不能为空'],
    ["username","regex=/^[A-Za-z]+$/",'只能是a-z'],
    ["username","minlength=3",'姓名必须大于3个字符'],
    ["username","maxlength=10",'姓名必须小于10个字符'],
    ["email","required",'邮箱必填'],
    ["email","email",'邮箱格式']
]);

其中第三个参数可以是function,比如

 代码如下 复制代码

F.addRule([
    ["username","required",function(){ alert('姓名不能为空') }],
    .....
]);

全局的报错也支持function(接收参数为错误的数组),

 代码如下 复制代码

errShow : function(data){
    var wrongList = document.getElementById('wrongList'), html = [];
    wrongList.innerHTML = '';
    for(var i =0; i '+data[i].msg+'');
    }
    wrongList.innerHTML = html.join('');
}

API

regex : 正则, (regex=/^[A-Za-z]+$/ )
required : 必填内容,针对input,textarea
minlength : 最小字符长度 (minlength=3)
maxlength : 最大字符长度 (maxlength=10)
number : 数字
alpha : 字母(大小写都可)
string : 字母,数字,下划线
email : 邮件格式
telphone : 电话
mobile : 手机
greaterthan : 大于某个值,或者某个input中的值 (greaterthan=5 或者 greaterthan=字段名 )
lessthan : 小于某个值,用法同上
equal : 等于某个值,或者数组(数组以|分隔)中的某个值,或者字段 (equal=66 或者 equal=字段名 或者 equal='aa|bb|cc' )
unequal : 不等于某个值,用法同上

notselect :不能选择的值,指的是select中option的value,或者 radio/checkbox数组中某一个的value (notselect=字符串或者数字或者数组)
shouldselect : 必须选中,用法同上

minselect : 最少选中几项
maxselect : 最多选择几项

 代码如下 复制代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      JavaScript form validator Example
    </title>
    <style type="text/css">
html,body,div,form,ul,li,h1{margin:0;padding:0;font-size: 12px;}
ul{list-style: none;}
.inlineWrap{letter-spacing: -0.31em;*letter-spacing: normal;*word-spacing: -0.43em;}
.inlineBlock{display: inline-block;zoom: 1;*display: inline;letter-spacing: normal;word-spacing: normal;vertical-align: top;}
#wrap{padding:30px;}
#wrap h1{background: #0866c6;font-family: 'Microsoft YaHei';font-size: 24px;line-height: 40px;color: #fff;padding-left: 20px;}

        /*form list start*/
        .formList{padding:20px;}
        .formList li{position:relative;display: block;margin-top: 10px;overflow: hidden;}
        .formList li label{width:170px;text-align:right;color:#0866c6;display: inline-block;line-height: 30px;float:left;}
        .formList li span{display:block;margin-left: 190px;line-height: 30px;}

        textare, input{display:inline-block;height:20px;padding:4px 6px;line-height:20px;color:#555555;vertical-align:middle;-webkit-border-radius:  0;-moz-border-radius:  0;border-radius:  0;outline:none;max-width:90%;width:200px;}
        textarea, input, select{background-color:#ffffff;border:1px solid #cccccc;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s, box-shadow linear .2s;transition:border linear .2s, box-shadow linear .2s;}
        select{padding:5px;font-size:12px;color:#555;border:1px solid #ccc;}
        textarea:focus,input:focus,select:focus{border-color:rgba(82,168,236,0.8);border-color:#0866c69;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(82,168,236,.6);}
        input[type=radio]:focus{box-shadow: none;}

        .btn{font-size:12px;border:1px solid #bbb;background: #0866c6;color: #fff;text-decoration:none;height:30px;vertical-align: baseline;width:100px;cursor: pointer;}
        .btn:hover{background: #1b58b8;color: #fff;}

        .error_strings{padding:10px;color: #db4f33;line-height: 20px;font-size: 12px;border: 10px solid #0866c6;display: none;position: fixed;top:90px;left:600px;}

        .formList li span label{display: inline-block;color: #000;font-weight: normal;width:auto;margin-right: 10px;}
        .formList li span label input{width: auto;}
        .formList li .error_strings{display: inline-block;margin:0;padding:0;background: none;border:none;border-left:5px solid #db4f33;line-height: 14px;padding-left: 5px;margin-left: 10px;position: relative;top:0px;left:0px;}

        #wrongList{width:200px;display: inline-block;margin: 50px;}
        #wrongList li{width:100%;background:#3B70E1;color: #fff;padding:5px 10px;line-height: 18px;margin: 5px 0px;}

        .setting {padding-top:30px;}
        .setting label{width:auto;}
        .setting label input{width:auto;}
    </style>

 
</head>
 
  <body>

  <div id="wrap" class="inlineWrap">

      <div class="inlineBlock" style="width:600px;float:left;">
          <h1>Form Validator</h1>

          <div class="setting formList" style="overflow: hidden;border-bottom: 1px solid #ececec;">
              <div style="float:left;width:300px;">

                  <div>
                      <label><input type="radio" value="0" name="shownum" checked>只显示一条错误</label>
                      <label><input type="radio" value="1" name="shownum">显示多条</label>
                  </div>
                  <div><label><input type="radio" value="1" name="timely" checked>实时显示</label></div>
                  <div>
                      <label><input type="radio" value="alert" name="wrongtype" checked>alert</label>
                      <label><input type="radio" value="single" name="wrongtype">单条显示</label>
                      <label><input type="radio" value="multiple" name="wrongtype">合并显示</label>
       <label><input type="radio" value="function" name="wrongtype">函数</label>
                  </div>
                  <input type="button" class="btn" value="重新初始化" onclick="initV()">
              </div>
              <div style="margin-left: 300px;line-height: 20px;color: green;font-weight: bold;">
                  默认设置:<br/>
                  只显示一条错误信息<br/>
                  实时显示关闭<br/>
                  报错样式为alert
              </div>
          </div>

          <form action="/" name="myform" id="myform">
              <ul class="formList">
    
    <li>
                    <span>
                        <input type="submit" class="btn" value="Submit" />
                    </span>
                  </li>
    
                  <li>
                      <label>姓名</label>
                        <span>
                            <input type="text" name="username" />
                        </span>
                  </li>
                  <li>
                      <label>邮箱</label>
            <span>
                <input type="text" name="email" />
            </span>
                  </li>
                  <li>
                      <label>电话</label>
            <span>
                <input type="text" name="telphone" />
            </span>
                  </li>
                  <li>
                      <label>手机</label>
            <span>
                <input type="text" name="mobile" />
            </span>
                  </li>
      <li>
                      <label>URL</label>
            <span>
                <input type="text" name="url" />
            </span>
                  </li>
                  <li>
                      <label>数字(5-10)</label>
                <span>
                    <input type="text" name="than" />
                </span>
                  </li>
                  <li>
                      <label>大于上面</label>
                <span>
                    <input type="text" name="greaterPrev" />
                </span>
                  </li>
                  <li>
                      <label>等于66</label>
                <span>
                    <input type="text" name="equalNum" />
                </span>
                  <li>
                      <label>等于上面</label>
                <span>
                    <input type="text" name="equalPrev" />
                </span>
                  </li>
                  <li>
                      <label>不能等于99</label>
                <span>
                    <input type="text" name="unequalNum" />
                </span>
                  </li>
                  <li>
                      <label>不能等于上面</label>
                    <span>
                        <input type="text" name="unequalPrev" />
                    </span>
                  </li>
                  <li>
                      <label>不能等于11,22,33</label>
                    <span>
                        <input type="text" name="unequalArr" />
                    </span>
                  </li>
                  <li>
                      <label>不能等于aa,bb,cc</label>
                    <span>
                        <input type="text" name="unequalArrStr" />
                    </span>
                  </li>

                  <li>
                      <label>只能从ab,ac,ad中取</label>
                    <span>
                        <input type="text" name="equalArr" />
                    </span>
                  </li>

                  <li>
                      <label>不能选择第一项0</label>
                <span>
                    <select name="select">
                        <option value="0">请选择</option>
                        <option value="1s">选我吧</option>
                        <option value="2">选谁呀</option>
                    </select>
                </span>
                  </li>

                  <li>
                      <label>必须选中第一个,不能选第三个</label>
                        <span>
                            <label><input type="checkbox" name="checkNum" value="1" />第一项</label>
                            <label><input type="checkbox" name="checkNum" value="2" />第二项</label>
                            <label><input type="checkbox" name="checkNum" value="3" />第三项</label>
                        </span>
                  </li>

                  <li>
                      <label>必须选中第1,3个</label>
                        <span>
                            <label><input type="checkbox" name="checkMore" value="1" />第一项</label>
                            <label><input type="checkbox" name="checkMore" value="2" />第二项</label>
                            <label><input type="checkbox" name="checkMore" value="3" />第三项</label>
                            <label><input type="checkbox" name="checkMore" value="4" />第四项</label>
                        </span>
                  </li>

                  <li>
                      <label>选中数大于2,小于4(不能选择1,2)</label>
                     <span>
                            <label><input type="checkbox" name="checkLen" value="1" />第一项</label>
                            <label><input type="checkbox" name="checkLen" value="2" />第二项</label>
                            <label><input type="checkbox" name="checkLen" value="3" />第三项</label>
                            <label><input type="checkbox" name="checkLen" value="4" />第四项</label>
                             <label><input type="checkbox" name="checkLen" value="5" />第五项</label>
                             <label><input type="checkbox" name="checkLen" value="6" />第六项</label>
                             <label><input type="checkbox" name="checkLen" value="7" />第七项</label>
                        </span>
                  </li>

                  <li>
                      <label>必选,不能选中3</label>
                        <span>
                            <label><input type="radio" name="checkRadio" value="1" />第一项</label>
                            <label><input type="radio" name="checkRadio" value="2" />第二项</label>
                            <label><input type="radio" name="checkRadio" value="3" />第三项</label>
                            <label><input type="radio" name="checkRadio" value="4" />第四项</label>
                             <label><input type="radio" name="checkRadio" value="5" />第五项</label>
                             <label><input type="radio" name="checkRadio" value="6" />第六项</label>
                             <label><input type="radio" name="checkRadio" value="7" />第七项</label>
                        </span>
                  </li>
     
      <li>
                      <label>必填</label>
                        <span>
                            <textarea name="textarea"></textarea>
                        </span>
                  </li>

                  <li>
                    <span>
                        <input type="submit" class="btn" value="Submit" />
                    </span>
                  </li>
              </ul>
          </form>

      </div>

      <div class="inlineBlock" style="display: block;margin-left: 650px;">
          <ul id="wrongList">
          </ul>
      </div>

  </div>

 

<script language="JavaScript" src="validator.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">

document.forms['myform'].onsubmit = function(){
 alert ('已经通过验证,要进行提交操作');
    return false;
}

//errShow : function(data){
//    var wrongList = document.getElementById('wrongList'), html = [];
//    wrongList.innerHTML = '';
//    for(var i =0; i < data.length ; i += 1){
//        html.push('<li>'+data[i].msg+'</li>');
//    }
//    wrongList.innerHTML = html.join('');
//}

var F = Validator('myform',{
    errPar : 'span',
    together : false, //显示一条错误,还是同时显示多条错误,默认false(只显示一条)
    errShow : 'alert', //错误显示样式,默认为alert,支持字符串(alert,single,multiple),自定义function(string || array())
    timely : true //开启实时验证,默认关闭
});

F.addRule([
    ["username","required",'姓名不能为空'],
    ["username","regex=/^[A-Za-z]+$/",'只能是a-z'],
    ["username","minlength=3",'姓名必须大于3个字符'],
    ["username","maxlength=10",'姓名必须小于10个字符'],
    ["email","required",'邮箱必填'],
    ["email","email",'邮箱格式'],
    ["telphone","required",'电话必填'],
    ["telphone","telphone",'电话格式错误'],
    ["mobile","required",'手机必填'],
    ["mobile","mobile",'手机格式错误'],
 ["url","required",'url必填'],
 ["url","url",'url格式错误'],
    ["than","greaterthan=5",'必须大于5'],
    ["than","lessthan=10",'必须小于10'],
    ["greaterPrev","greaterthan=than",'必须大于上面的值'],
    ["equalNum","equal=66",'必须等于66'],
    ["equalPrev","equal=equalNum",'必须等于上面的66'],
    ["unequalNum","unequal=99",'不能等于99'],
    ["unequalPrev","unequal=unequalNum",'不能等于上面'],
    ["unequalArr","unequal='11|22|33'",'不能等于11,22,33'],
    ["unequalArrStr","unequal='aa|bb|cc'",'不能等于aa,bb,cc'],
    ["equalArr","equal='ab|ac|ad'",'只能填ab,ac,ad'],
    ["select","notselect=0",'不能选择第一项0'],
    ["checkNum","notselect=3",'不能选3'],
    ["checkNum","shouldselect=1",'必须选中第一个'],
    ["checkMore","shouldselect='1|3'",'必须选中1,3'],
    ["checkLen","notselect='1|2'",'不能选择1,2'],
    ["checkLen","minselect=2",'选中不能少于2项'],
 ["checkLen","maxselect=4",'选中不能大于4项'],
    ["checkRadio","shouldselect",'必须选泽这里'],
    ["checkRadio","notselect=3",'不能选中第三项'],
 ["textarea","required",'内容不能为空']
]);

/*F.removeRule([
 ['username','required'],
 ['email','required']
]);*/

    function initV(){
        var numBox = document.getElementsByName('shownum'), timeBox = document.getElementsByName('timely'), wrongBox = document.getElementsByName('wrongtype'), shownum, timely, wrongtype;
        for(var i = 0; i < numBox.length ; i += 1){
            if(numBox[i].checked == true){
                shownum = numBox[i].value;
            }
        }
        for(var j = 0; j < wrongBox.length ; j += 1){
            if(wrongBox[j].checked == true){
                wrongtype = wrongBox[j].value;
            }
        }
        for(var k = 0; k < timeBox.length ; k += 1){
            if(timeBox[k].checked == true){
                timely = timeBox[k].value;
            }
        }
  
  if(wrongtype == 'function'){
            wrongtype = function(data){
                var wrongList = document.getElementById('wrongList'), html = [];
                wrongList.innerHTML = '';
                for(var i =0; i < data.length ; i += 1){
                    html.push('<li>'+data[i].msg+'</li>');
                }
                wrongList.innerHTML = html.join('');
            }
        }

        shownum = shownum == 1 ? true : false;
        timely = timely == 1 ? true : false;

        F.init({
            errPar : 'span',
            together : shownum, //显示一条错误,还是同时显示多条错误,默认一条false
            errShow : wrongtype, //错误显示样式,默认为alert,支持字符串(alert,single,multiple),自定义function(string || array())
            timely : timely //开启实时验证
        });
    }

</script>
 
  </body>
</html>

时间: 2024-10-29 23:41:00

js原生态表单验证Validator类的相关文章

JS实现表单验证功能(验证手机号是否存在,验证码倒计时)_javascript技巧

废话不多说直接上代码 html代码: <form method="post" id="form_hroizon" enctype="multipart/form-data" action="/"> <input type="hidden" name="phoneTemplet" id="phoneTemplet"> <input type

js进行表单验证实例分析_javascript技巧

本文实例讲述了js进行表单验证的方法.分享给大家供大家参考.具体实现方法如下: 1. 传统的表单验证代码 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/199

jquery表单验证validator插件用法

这段时间工作上比较闲,总感觉不能让自己的技术荒废,于是又操起了老行,做起了小demo来. 这次我做了一个js版本的表单验证插件,总体的原理参照了jquery validate,但是在一些小方面还是有自己的创新. 这个插件主要功能有以下几点. 1.验证规则自定义 可以自己配置需要验证的表单项,对于验证通过或者错误时的处理,也可以自己决定,最大限度地保证了插件的灵活性. 2.验证方式多样 插件提供了丰富的验证种类,比如为空.长度.大小.相等.远程验证.数据类型验证等. 3.提示机制健全 当每次操作表

用ASP动态生成JS的表单验证代码

js|表单验证|动态 表单的验证是开发WEB应用程序中常遇到的一关.有时候我们必须保证表单的某些项必须填写.必须为数字.必须是指定的位数等等,这时候就要用到表单验证了,一般我们常用的表单验证有2种方式: 1.编写JavaScript或VBScript的表单验证函数,在客户端进行验证: 2.在表单提交后,使用ASP的方法Request.Form获取表单的输入值进行判断,然后返回结果,这是在服务端进行验证: 这两种方式都有其优缺点,比如第1种方式速度比较快,而且通常使用警告框的方式,用户能够很快的根

php 表单验证过滤类

class post_get{ private $array; #提交表单检测字段和检测要求 # $type;  缺省为更新 或$type ="Into";   public function _post_get($array,$type=""){   if(!$array) die(" Error!! ");    foreach ($array as $v)    {    $KK = $this->ck_split($v);    $

JS常用表单验证方法总结_javascript技巧

复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

JS调用表单验证,为什么return false表单依然submit?

表单提交前,都会有定义一个验证的方法以对用户提交的内容进行限定,今天写到了这个,但出现了一个好郁闷的东西,就是一点提交了,调用我自己写的一个CheckForm()方法时,我明明写了return false了,但它还是提交到服务器了,好不郁闷!然后仔细检查才发现,原来是漏了个return,下面先看出错的代码: <script src="../js/jquery-1.6.js" type="text/javascript"></script> &

js 常用表单验证正则收集

1. js 字符串长度限制  代码如下 复制代码 <script> function test() { if(document.a.b.value.length>50) { alert("不能超过50个字符!"); document.a.b.focus(); return false; } } </script> <form name=a onsubmit="return test()"> <textarea name

java正则表达式表单验证类工具类(验证邮箱、手机号码、qq号码等)_java

java使用正则表达式进行表单验证工具类,可以验证邮箱.手机号码.qq号码等 复制代码 代码如下: package util; import java.util.regex.Matcher;import java.util.regex.Pattern; /** * 使用正则表达式进行表单验证 *  */ public class RegexValidateUtil {    static boolean flag = false;    static String regex = ""