Home >Web Front-end >JS Tutorial >Simple example demonstration of jquery implementation of form validation_jquery

Simple example demonstration of jquery implementation of form validation_jquery

WBOY
WBOYOriginal
2016-05-16 15:30:281289browse

The example in this article describes the jquery implementation of form validation code. Share it with everyone for your reference. The details are as follows:
The screenshot of the running effect is as follows:

The specific code is as follows:

It’s easier to go directly to the plug-in to implement the code. It’s easier to explain around the code:

/*
描述:基于jquery的表单验证插件。
*/

(function ($) {
  $.fn.checkForm = function (options) {
    var root = this; //将当前应用对象存入root

    var isok = false; //控制表单提交的开关

    var pwd1; //密码存储

    var defaults = {
      //图片路径
      img_error: "img/error.gif",
      img_success: "img/success.gif",

      //提示信息
      tips_success: '', //验证成功时的提示信息,默认为空
      tips_required: '不能为空',
      tips_email: '邮箱地址格式有误',
      tips_num: '请填写数字',
      tips_chinese: '请填写中文',
      tips_mobile: '手机号码格式有误',
      tips_idcard: '身份证号码格式有误',
      tips_pwdequal: '两次密码不一致',

      //正则
      reg_email: /^\w+\@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/i, //验证邮箱
      reg_num: /^\d+$/,                 //验证数字
      reg_chinese: /^[\u4E00-\u9FA5]+$/,         //验证中文
      reg_mobile: /^1[3458]{1}[0-9]{9}$/,        //验证手机
      reg_idcard: /^\d{14}\d{3}?\w$/           //验证身份证
    };

    //不为空则合并参数
    if(options)
      $.extend(defaults, options);

    //获取(文本框,密码框,多行文本框),当失去焦点时,对其进行数据验证
    $(":text,:password,textarea", root).each(function () {
      $(this).blur(function () {
        var _validate = $(this).attr("check"); //获取check属性的值
        if (_validate) {
          var arr = _validate.split(' '); //用空格将其拆分成数组
          for (var i = 0; i < arr.length; i++) {
            //逐个进行验证,不通过跳出返回false,通过则继续
            if (!check($(this), arr[i], $(this).val()))
              return false;
            else
              continue;
          }
        }
      })
    })

    //表单提交时执行验证,与上面的方法基本相同,只不过是在表单提交时触发
    function _onSubmit() {
      isok = true;
      $(":text,:password,textarea", root).each(function () {
        var _validate = $(this).attr("check");
        if (_validate) {
          var arr = _validate.split(' ');
          for (var i = 0; i < arr.length; i++) {
            if (!check($(this), arr[i], $(this).val())) {
              isok = false; //验证不通过阻止表单提交,开关false
              return; //跳出
            }
          }
        }
      });
    }

    //判断当前对象是否为表单,如果是表单,则提交时要进行验证
    if (root.is("form")) {
      root.submit(function () {
        _onSubmit();
        return isok;
      })
    }


    //验证方法
    var check = function (obj, _match, _val) {
       //根据验证情况,显示相应提示信息,返回相应的值
      switch (_match) {
        case 'required':
          return _val &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_required, false);
        case 'email':
          return chk(_val, defaults.reg_email) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_email, false);
        case 'num':
          return chk(_val, defaults.reg_num) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_num, false);
        case 'chinese':
          return chk(_val, defaults.reg_chinese) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_chinese, false);
        case 'mobile':
          return chk(_val, defaults.reg_mobile) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_mobile, false);
        case 'idcard':
          return chk(_val, defaults.reg_idcard) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_idcard, false);
        case 'pwd1':
          pwd1 = _val; //实时获取存储pwd1值
          return true;
        case 'pwd2':
          return pwdEqual(_val, pwd1) &#63; showMsg(obj, defaults.tips_success, true) : showMsg(obj, defaults.tips_pwdequal, false);
        default:
          return true;
      }
    }


    //判断两次密码是否一致(返回bool值)
    var pwdEqual = function(val1, val2) {
      return val1 == val2 &#63; true : false;
    }


    //正则匹配(返回bool值)
    var chk = function (str, reg) {
      return reg.test(str);
    }

    //显示信息
    var showMsg = function (obj, msg, mark) {
      $(obj).next("#errormsg").remove();//先清除
      var _html = "<span id='errormsg' style='font-size:13px;color:gray;background:url(" + defaults.img_error + ") no-repeat 0 -1px;padding-left:20px;margin-left:5px;'>" + msg + "</span>";
      if (mark)
        _html = "<span id='errormsg' style='font-size:13px;color:gray;background:url(" + defaults.img_success + ") no-repeat 0 -1px;padding-left:20px;margin-left:5px;'>" + msg + "</span>";
      $(obj).after(_html);//再添加
      return mark;
    }
  }
})(jQuery);



Let’s talk about the implementation principle first:

First define the regular rules and the corresponding prompt information,

Add custom check attribute,

Then get the value of the check attribute, and separate multiple values ​​with spaces. Use split() to split it into an array, and call the check() method one by one to verify.

Then the displayed information is determined by the return value of the verification.

There are two special verifications here, namely:

1. Verify whether it is empty (required)

2. Are the two passwords consistent (pwd2)

Neither of these two uses regular expressions, because they are not used at all. Whether the two passwords are consistent, I wrote a separate method pwdEqual();

I have only written a few verification rules in the plug-in. If they are not enough, you can expand and add them by yourself.

Extension only takes 3 steps:

1. Add regular expression,

2. Add corresponding prompt information,

3. Add corresponding case processing in the check() method

Instructions for using the plug-in:

1. Add custom check attributes to the text boxes, password boxes, and multi-line text boxes that need to be verified in the form

2. Multiple format verifications are separated by spaces, such as (verifying required fields and email at the same time): check="required email"

3. If you want to verify whether the two passwords are consistent, use pwd1 and pwd2 together, as shown below:

pwd1 stores the value entered for the first time, and pwd2 stores the value entered for the second time. It’s okay if you only use pwd1, but if you only use pwd2, the verification will never pass.

DEMO sample code is given below:

<!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/1999/xhtml">
<head>
  <title>表单验证插件</title>
</head>
<body>
  <form id="myform" method="post" action="success.html">
    <ul>
      <li>
      邮箱:<input type="text" name="email" check="required email" />
      </li>
      <li>
      密码:<input type="password" check="required pwd1" />
      </li>
      <li>
      确认密码:<input type="password" check="required pwd2" />
      </li>
      <li>
      手机:<input type="text" name="num" check="required mobile" />
      </li>
      <li>
      数字:<input type="text" name="num" check="required num" />
      </li>
      <li>
      地址:<textarea cols="5" rows="5" check="required"></textarea>
      </li>
      <li>
      不加check验证的文本框:<input type="text" name="num" />
      </li>
    </ul>
    <input type="submit" value="提交" />
  </form>
  <script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
  <script src="js/jquery.similar.checkForm.js" type="text/javascript"></script>
  <script type="text/javascript">
    $("#myform").checkForm();
  </script>
</body>
</html>

Sample effect picture:

If the sample code is successfully submitted, it will jump to the success.html page, so you need to create a success.html yourself. You can write nothing in it.

However, as long as one verification fails, the jump will not be successful.

In addition, you may also need 2 pictures:

//Picture path
img_error: "img/error.gif",
img_success: "img/success.gif",

Uploaded here, right click and save as.

The above is the entire content of this article. I hope it can help everyone find a better way to master the implementation of jquery verification code.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn