前言
在项目中遇到了这样一个密码校验,要求:密码首字母大写;密码长度为8-16位;必须包括1-10个字母;必须包含1-10个数字;必须包含1-10个标点符号;禁止包含的符号[%, +, <, >, /],原本是想写个正则,奈何无才,想不出来,只好用正则和js来完成。
代码
// this.sendToast()这个用来提示用户的
updatePass () {
// let reg = new RegExp(/^[A-Z](?=(?:\D*\d){1,10})(?=(?:\W\w){1,10})/)
if (this.newPass !== '') {
let first = new RegExp(/^[A-Z]/)
// 必须以大写字母开头
if (!first.test(this.newPass.charAt(0))) return this.sendToast()
// 密码长度
var flag = Boolean(this.newPass.length >= 8 && this.newPass.length <= 16)
if (!flag) return this.sendToast()
// 密码中数字在1-10
let num = this.newPass.replace(/[^0-9]/g, '')
if (!Boolean(num.length >= 1 && num.length <= 10)) return this.sendToast()
// 密码中字母在1-10,必须包含大小写,在这把首位截取掉了
let word = this.newPass.slice(1).replace(/[^A-Za-z]/g, '')
if (word.length == 1) {
if (!(/^[a-z]/.test(word))) return this.sendToast()
} else if (!Boolean(word.length > 1 && word.length <= 10)) {
this.sendToast()
}
// 密码字符串数组
let spec = this.newPass.split("")
let arr = []
spec.forEach(e => {
// 禁止包含的字符
if (e == '%' || e == '+' || e == '<' || e == '>' || e == '/') {
this.sendToast()
}
// 这个条件输出的是数字和字母,如果不加!输出的是全部的
if (!(/[^A-Za-z]/.test(e)) || !(/[^0-9]/.test(e))) {
arr.push(e)
}
})
console.log('非标点符号项', arr);
// 筛选所有项和非标点项(只有数字和字母)不同项
let others = spec.filter(item => {
return arr.indexOf(item) == -1
})
console.log('标点符号项', others);
// 包含的标点符号个数在1-10
if (!Boolean(others.length >= 1 && others.length <= 10)) return this.sendToast()
}
if (this.newPass !== this.confirmNewPass) return this.$toast('两次输入新密码不一致,请重新输入')
}
各位友友们要是有更简单的方式,欢迎在下方指教~~~~