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

时间:2019-04-19 15:16:15

标签: javascript reactjs refactoring

在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')
  }; 

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

1 个答案:

答案 0 :(得分:1)

也许像下面这样就足够了。如果您提供了一般错误消息,例如"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()
}