表单验证——JavaScript和Jquery版

1.轻量级的JavaScript表单验证

在应用中引用 validator.min.js 文件

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

实例:

<form id="example_form">
    <div>
        <label for="email">邮箱验证</label>
        <input type="email" name="email" id="email" class="form-control" placeholder="Email">
    </div>
</form>
<script type="text/javascript">
  var validator = new Validator('example_form',[
    {
        //name 字段
        name: 'email',
        display:"你输入的不{{email}}是合法邮箱|不能为空|太长|太短",
        // 验证条件
        rules: 'is_emil|max_length(12)|required'
        // rules: 'valid_email|required|max_length(12)|min_length(2)'
    },{
        //name 字段
        name: 'sex',
        display:"请你选择性别{{sex}}",
        // 验证条件
        rules: 'required'
    }
  ],function(obj,evt){
      if(obj.errors){
          // 判断是否错误
      }
  })
</script>

说明:

new Validator(formName, option, callback)

formName

formName 是标签中<form> 中的 id 或者 name 的值,如上面的example_form

option

  • name -> input 中 name 对应的值
  • display -> 验证错误要提示的文字 {{这个中间是name对应的值}}
  • rules -> 一个或多个规则(中间用|间隔)

    • is_email -> 验证合法邮箱
    • is_ip -> 验证合法 ip 地址
    • is_fax -> 验证传真
    • is_tel -> 验证座机
    • is_phone -> 验证手机
    • is_url -> 验证URL
    • required -> 是否为必填
    • max_length -> 最大字符长度
    • min_length -> 最小字符长度

自定义正则

自定义正则,以regexp_开始

{
  //name 字段
  name: 'sex',
  // 对应下面验证提示信息
  display:"请你选择性别{{sex}}|请输入数字",
  //自定义正则`regexp_num`
  regexp_num:/^[0-9]+$/,
  // 验证条件,包括应用自定义正则`regexp_num`
  rules: 'required|regexp_num'
}

字符串验证:

var v = new Validator();
v.isEmail('wowohoo@qq.com'); // -> 验证合法邮箱  |=> 返回布尔值
v.isIp('192.168.23.3'); // -> 验证合法 ip 地址  |=> 返回布尔值
v.isFax(''); // -> 验证传真  |=> 返回布尔值
v.isPhone('13622667263'); // -> 验证手机  |=> 返回布尔值
v.isTel('021-324234-234'); // -> 验证座机  |=> 返回布尔值
v.isUrl('http://JSLite.io'); // -> 验证URL  |=> 返回布尔值
v.maxLength('JSLite',12); // -> 最大长度  |=> 返回布尔值
v.minLength('JSLite',3); // -> 最小长度  |=> 返回布尔值
v.required('23'); // -> 是否为必填(是否为空)  |=> 返回布尔值

表单中验证

点击按submit按钮验证和没有submit验证的区别:没有submit验证需要在结尾加上

validator.validate()

 

 

2.Jquery  .validate()表单验证

validate([options]):

1.debug(default: false)

$(".selector").validate({
  debug: true
});

启用调试模式。如果为true,表单不会提交,并且错误显示在控制台(如果window.console属性存在,将检查)上,如试图帮助建立验证约缺少方法和其他调试消息警告。。尝试当一个表单刚刚提交,而不是验证停止提交启用。

2.submitHandler (default: native form submit)

ex:

Submits the form via Ajax when valid.

$(".selector").validate({
  submitHandler: function(form) {
    $(form).ajaxSubmit();
  }
});

ex:

使用submitHandler处理一些东西,然后使用默认的提交。注意,form是指一个DOM元素,这样一来验证不会再次触发。

3.invalidHandler

无效表单提交时,回调客户端代码。调用事件对象作为第一个参数,验证为第二个参数。

ex:

表单上显示错误消息,表明当用户试图提交无效表单有多少个字段是无效的。

$(".selector").validate({
  invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});

4.ignore (default: ":hidden")

验证时,简单地筛选出需要忽略的元素。

ex:Ignores all elements with the class "ignore" when validating.

$("#myform").validate({
  ignore: ".ignore"
});

5.rules (default: rules are read from markup (classes, attributes, data))

ex:

$(".selector").validate({
  rules: {
    // simple rule, converted to {required:true}
    name: "required",
    // compound rule
    email: {
      required: true,
      email: true
    }
  }
});
$(".selector").validate({
  rules: {
    contact: {
      required: true,
      email: {
        depends: function(element) {
          return $("#contactform_email").is(":checked");
        }
      }
    }
  }
});
$(".selector").validate({
  rules: {
    // at least 15€ when bonus material is included
    pay_what_you_want: {
      required: true
      min: {
        // min needs a parameter passed to it
        param: 15,
        depends: function(element) {
          return $("#bonus-material").is(":checked");
        }
      }
    }
  }
});

6.messages (default: the default message for the method used)

ex:

$(".selector").validate({
  rules: {
    name: "required",
    email: {
      required: true,
      email: true
    }
  },
  messages: {
    name: "Please specify your name",
    email: {
      required: "We need your email address to contact you",
      email: "Your email address must be in the format of name@domain.com"
    }
  }
});
$(".selector").validate({
  rules: {
    name: {
      required: true,
      minlength: 2
    }
  },
  messages: {
    name: {
      required: "We need your email address to contact you",
      minlength: jQuery.validator.format("At least {0} characters required!")
    }
  }
});

7.groups

Use a table layout for the form, placing error messags in the next cell after the input.

$("#myform").validate({
  groups: {
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
    if (element.attr("name") == "fname" || element.attr("name") == "lname" ) {
      error.insertAfter("#lastname");
    } else {
      error.insertAfter(element);
    }
  }
});

8.showErrors

Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.

$(".selector").validate({
  showErrors: function(errorMap, errorList) {
    $("#summary").html("Your form contains "
      + this.numberOfInvalids()
      + " errors, see details below.");
    this.defaultShowErrors();
  }
});

 

posted @ 2016-09-25 15:40  张三的美丽家园  阅读(262)  评论(0编辑  收藏  举报