简体   繁体   中英

How can I DRY up this code?

I want to iterate over the formProps object and check for the keys and set the value on the same keys onto the errors object.

if (!formProps.email) {
    errors.email = "Please enter an email"
}
if (!formProps.password) {
  errors.password = "Please enter a password"
}
if (!formProps.passwordConfirm) {
  formProps.passwordConfirm = "Please enter a password confirmation"
}
if (formProps.password != formProps.passwordConfirm) {
  errors.password = "Passwords must match"
}

This will better as sending array because you can show all errors at same time

var errors = [];
!formProps.email ? errors.push("Please enter an email") : null;
!formProps.password ? errors.push("Please enter a password") : null;
!formProps.passwordConfirm ? errors.push("Please enter a password confirmation") : null;
formProps.password != formProps.passwordConfirm ? errors.push("Passwords must match") : null;
if(errors.length > 0){
    return errors;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM