有没有人用过新的yup-password验证?我试过了,但失败了。我参考了文档,但无法理解它。有人能帮帮忙吗?Link to the yup-password documentation
发布于 2021-02-09 09:29:38
yup-password是一个yup插件,所以你首先需要安装yup。
运行以下命令以安装yup和yup-password
$ npm install yup yup-password然后,如文档所示,在您的项目中包含这两个包,并键入您的模式。
// 1. import `yup`
const yup = require('yup')
// 2. setup `yup-password`
// this line extends yup's StringSchema with the
// methods shown in yup-password's documentation
require('yup-password')(yup)
// 3. build your validation schema
const schema = yup.object().shape({
username: yup.string().email().required(),
password: yup.string().password().required(),
})
// The user input
const input = {
username: 'user@example.com',
// since the following password does not meet the
// default criteria, it will fail validation.
password: 'my password',
}
// 4. run the validation
// using async/await
void (async () => {
try {
// the `{ abortEarly: false }` is optional, but I'm adding there
// so that we can see all the failed password conditions.
const res = await schema.validate(input, { abortEarly: false })
} catch (e) {
console.log(e.errors) // => [
// 'password must be at least 8 characters',
// 'password must contain at least 1 upper-cased letter',
// 'password must contain at least 1 number',
// 'password must contain at least 1 symbol',
// ]
}
})()
// using promises
schema
.validate(input, { abortEarly: false })
.then(() => console.log('success!'))
.catch(e => console.log('validation failed: ' + e.errors.join(', ')))如果您对默认密码条件不满意,可以使用添加的其余方法根据自己的喜好自定义行为。例如:
const schema = yup
.string()
// at least 3 lowercase characters
.minLowercase(3)
// at least 2 uppercase characters
.minUppercase(2)
// and at least 6 numbers
.minNumber(6)
schema
.validate('my password')
.then(() => console.log('success'))
.catch(e => console.log('failed: ' + e.errors.join(', ')))我希望这能把事情弄清楚一点。
https://stackoverflow.com/questions/66058060
复制相似问题