getFieldDecorator规则密码包含小写大写字母和数字?

问题描述 投票:1回答:2

我正在开发一个react应用程序并且视图是使用Ant Design构建的,我正在验证表单,我不知道如何验证传递以包含大小写和数字的字符。

这是我用ant设计验证的字段:

                            <FormItem>
                                {getFieldDecorator('password', {
                                    rules: [{required: true, message: 'Please input your password!'}, {
                                    validator: this.validateToNextPassword,}],
                                })(
                                    <StyledInput placeholder="Password" type="password"/>
                                )}
                            </FormItem>
                            <FormItem>
                                {getFieldDecorator('Re-enterPassword', {
                                    rules: [{required: true, message: 'Please confirm your password!',}, {
                                    validator: this.compareToFirstPassword,}],
                                })(
                                    <StyledInput placeholder="Re-enter password" type="password" onBlur={this.handleConfirmBlur}/>
                                )}
                            </FormItem>

这是用于验证传递的函数:

handleConfirmBlur = (e) => {
            const value = e.target.value;
            this.setState({ confirmDirty: this.state.confirmDirty || !!value });
        }

        compareToFirstPassword = (rule, value, callback) => {
            debugger;
            const form = this.props.form;
            if (value && value !== form.getFieldValue('password')) {
                callback('Two passwords that you enter is inconsistent!');
            } else {
                callback();
            }
        }

        validateToNextPassword = (rule, value, callback) => {
            debugger;
            const form = this.props.form;
            if (value && this.state.confirmDirty) {
                form.validateFields(['confirm'], { force: true });
            }
            callback();
        }

此代码验证pass字段是否为空,并检查两个密码是否相似,但我需要验证传递以包含小写字符大写字母和数字。

javascript reactjs antd
2个回答
0
投票

您可以使用正则表达式:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]+$

(?=.*[a-z]) - 至少一封小写字母

(?=.*[A-Z]) - 至少一个首都

(?=.*\d) - 至少一位数

[a-zA-Z\d]+ - 仅允许使用字母和数字(定义允许字符的子集)


0
投票

代码中的Validator仅比较两个密码。你应该为rules数组添加另一个验证器(它可以接收任意数量的验证器)

rules: [{...yourValidator}, { message: 'Password should contain uppercase letter etc'}, validator: this.strongValidator]

并写strongValidator函数:

strongValidator = (rule, value, callback) => {
  if(!value.match(digitsRegex) || !value.match(uppercaseRegex)) {
    return callback(true)
  }
  callback()
}

您还可以选择validateFirst以在第一个错误时停止验证

© www.soinside.com 2019 - 2024. All rights reserved.