learnerforlife
learnerforlife

Reputation: 199

Looking for suggestions on how to clean up some conditional statements

Developing a validation function in React. I fairly new and don't want to develop any bad habits while I'm learning so I'm looking for suggestions on how to clean up a block of code i have here.

The function checks input fields and if they're blank, it attaches the appropriate message to an array. Once all input fields are checked, if that array is empty then proceed to submitting form. If that array contains error messages then the message is displayed to screen (not shown)

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

Just looking for ways to clean up my conditional statements, if possible! Thanks

Upvotes: 1

Views: 62

Answers (1)

lux
lux

Reputation: 8455

Perhaps something like the below would suffice. You could simplify this greatly if you provided a generic error message such as "Missing required value: <keyName>", as opposed to something specific for the field.

You'll also want to do a manual check to ensure password === confirmPassword, but I think you'll be able to work that piece out.

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

Validation Map

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'
    }
  ],
}    

Validator

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()
}

Upvotes: 1

Related Questions