How to using validate.js with custom rule
表单需要对手机号码字段做验证,找到了一个能匹配目前几乎所有号段的正则表达式:
/^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/
Form
<form name='join' method='post' action=''>
...
<input id="id_mobile" name="mobile" type="text">
<button type="submit">提交</button>
</form>
JS
var validator = new FormValidator('join', [{
name: 'id_mobile',
display: 'required',
rules: '!callback_mobile'
}], function(errors, event) {
if (errors.length > 0) {
$('#id_mobile').next('p').text(errors[0].message)
alert(errors[0].message)
}
})
validator.registerCallback('mobile', function(value) {
var reg = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/
if (reg.test(value)) {
return true
}
return false
}).setMessage('mobile', '请输入有效的手机号码')
validate.js 很轻,压缩以后只有2.1kb
。
调用自定义规则时,名称前面要加 callback_
,例如 callback_mobile
,如果需要强制验证,可以在验证规则前面加一个 !
感叹号。