gpt4 book ai didi

javascript - 寻找有关如何清理某些条件语句的建议

转载 作者:行者123 更新时间:2023-11-30 19:37:39 25 4
gpt4 key购买 nike

在 React 中开发验证函数。我是新手,不想在学习期间养成任何坏习惯,所以我正在寻找有关如何清理我这里的代码块的建议。

该函数检查输入字段,如果它们是空白的,它会将适当的消息附加到一个数组中。检查所有输入字段后,如果该数组为空,则继续提交表单。如果该数组包含错误消息,则该消息将显示在屏幕上(未显示)

validation = (event) => {
event.preventDefault();
let errors = []
const {firstName, lastName, emailAddress, password, confirmPassword} = {...this.state}

if(firstName.length === 0) errors.push('Please provide a value for First Name');
if(lastName.length === 0) errors.push('Please provide a value for Last Name');

if(password.length === 0){
errors.push('Please provide a value for Password');
}else if(password !== confirmPassword){
errors.push('Passwords do not match');
};

if(emailAddress.length === 0) {
errors.push('Please provide a value for Email Address');
}else if(!emailRegex.test(emailAddress)){
errors.push('Invalid email address');
};

this.setState({errors: errors})

if(errors.length === 0) this.logIn()
}

logIn = () => {
console.log('good to go')
};

如果可能的话,只是在寻找清理我的条件语句的方法!谢谢

最佳答案

也许像下面这样的东西就足够了。如果您提供一个通用的错误消息,例如 "Missing required value: <keyName>",您可以大大简化这个过程。 ,而不是特定于该领域的东西。

您还需要进行手动检查以确保 password === confirmPassword ,但我认为您将能够解决这个问题。

const emailRegex = <your regex>;
const hasLength = val => val && val.length !== 0;

验证图

const validators = {
firstName: {
validate: hasLength,
message: 'Please provide a value for First Name'
},
lastName: {
validate: hasLength,
message: 'Please provide a value for Last Name'
},
password: {
validate: hasLength,
message: 'Please provide a value for Password'
},
emailAddress: [{
validate: hasLength,
message: 'Please provide a value for Email Address'
},
{
validate: val => !emailRegex.test(val),
message: 'Invalid email address'
}
],
}

验证器

validation = (event) => {
event.preventDefault();
let errors = []
const state = {...this.state};

Object
.keys(state)
.forEach(key => {
let validator = validators[key];
if (!validator) return;
if (!Array.isArray(validator)) {
validator = [validator]
}
validator.forEach(v => {
if (!v.validate(state[key])) {
errors.push(v.message)
}
})
});

this.setState({errors: errors})

if (errors.length === 0) this.logIn()
}

关于javascript - 寻找有关如何清理某些条件语句的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com