问候,我需要验证密码表单除所需字段外必须至少有一个大写字母、至少有小写字母、至少一个数字和至少一个以下字符"#?!@$%^&*-"我正在使用此软件包https://vuelidate.js.org/
编辑
或此的REGEX
只需在Vuelidate验证中添加一个带有所需规则的自定义函数。
validations: {
password: {
required,
// minLength: minLength(8) // I assume you'd want something like this too
valid: function(value) {
const containsUppercase = /[A-Z]/.test(value)
const containsLowercase = /[a-z]/.test(value)
const containsNumber = /[0-9]/.test(value)
const containsSpecial = /[#?!@$%^&*-]/.test(value)
return containsUppercase && containsLowercase && containsNumber && containsSpecial
}
}
}
将每个需求分解为一个单独的函数可能会有所帮助,这样您就可以为每个需求设置不同的错误消息(这将有助于指导用户需要修复什么(。
validations: {
password: {
required,
// minLength: minLength(8) // I assume you'd want something like this too
containsUppercase: function(value) {
return /[A-Z]/.test(value)
},
containsLowercase: function(value) {
return /[a-z]/.test(value)
},
containsNumber: function(value) {
return /[0-9]/.test(value)
},
containsSpecial: function(value) {
return /[#?!@$%^&*-]/.test(value)
}
}
}
要扩展Keegan的答案,可以在密码验证中包含helpers.withMessage
方法以包含自定义错误消息。我合并了正则表达式,使其更容易、更简单地处理错误消息。
import useVuelidate from '@vuelidate/core'
import { helpers, required, email, minLength, maxLength, sameAs } from '@vuelidate/validators'
export default {
setup () {
return {
v$: useVuelidate({
$lazy: true,
$autoDirty: true,
})
}
},
validations () {
return {
firstName: { required, minValue: minLength(4), maxValue: maxLength(40), },
lastName: { required, minValue: minLength(4), maxValue: maxLength(40), },
email: { required, email, },
password: {
required,
minLength: minLength(6),
containsPasswordRequirement: helpers.withMessage(
() => `The password requires an uppercase, lowercase, number and special character`,
(value) => /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])/.test(value)
),
},
confirmPassword: { required, sameAsPassword: sameAs(this.password) }
}
},
data() {
return {
firstName: '',
lastName: '',
email: '',
password: '',
confirmPassword: '',
}
},
...