首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Yup-密码验证

Yup-密码验证
EN

Stack Overflow用户
提问于 2021-02-05 13:35:54
回答 1查看 669关注 0票数 0

有没有人用过新的yup-password验证?我试过了,但失败了。我参考了文档,但无法理解它。有人能帮帮忙吗?Link to the yup-password documentation

EN

回答 1

Stack Overflow用户

发布于 2021-02-09 09:29:38

yup-password是一个yup插件,所以你首先需要安装yup

运行以下命令以安装yupyup-password

代码语言:javascript
复制
$ npm install yup yup-password

然后,如文档所示,在您的项目中包含这两个包,并键入您的模式。

代码语言:javascript
复制
// 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(', ')))

如果您对默认密码条件不满意,可以使用添加的其余方法根据自己的喜好自定义行为。例如:

代码语言:javascript
复制
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(', ')))

我希望这能把事情弄清楚一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66058060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档