JS封装表单验证工具

示例

validate.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 验证邮箱
const email = email => {
const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
if(reg.test(email)) return true
return false
}

// 验证最小长度
const min = (str, len) => {
if(str.length >= len) return true
return false
}

// 验证最大长度
const max = (str, len) => {
if(str.length <= len) return true
return false
}

// 是否是相同的字符串
const confirm = (str1, str2) => {
if(str1 == str2) return true
return false
}

// 验证手机号
const phone = phone => {
const reg = /^1[3-9][0-9]{9}$/;
if(reg.test(phone)) return true
return false
}

module.exports = {
email,
min,
max,
confirm,
phone
}

使用示例(小程序)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const validate = require('../../utils/validate')

checkInput() {
// 收集表单数据
const {name, email, password, password_confirmation} = this.data
// 对表单数据进行验证
const checkName = validate.min(name, 2)
const checkEmail = validate.email(email)
const checkPassword = validate.min(password, 6)
const checkConfirm = validate.confirm(password, password_confirmation)

// 验证用户名
if(!checkName) {
this.setData({error_name: '昵称最少两个字符'})
} else {
this.setData({error_name: ''})
}

// 验证邮箱格式
if(!checkEmail) {
this.setData({error_email: '邮箱格式不正确'})
} else {
this.setData({error_email: ''})
}

// 验证密码格式
if (!checkPassword) {
this.setData({ error_password: '密码最少6位'})
} else {
this.setData({error_password: ''})
}

// 确认密码
if (!checkConfirm) {
this.setData({ error_password_confirm: '两次密码不一致'})
} else {
this.setData({error_password_confirm: ''})
}

// 全部验证通过返回 true
if(checkName && checkEmail && checkPassword && checkConfirm) return true
return false
}

JS封装表单验证工具

http://example.com/index/ad29/

作者

WZJ

发布于

2021-07-10

许可协议

评论