Thursday, 21 January 2021

Refactoring validation handling and messaging

I am working on a react project that uses redux forms. I've looped through the fields to check their validation requirements if need be. This stack works well - but I know I should re-visit this to place parts inside a function

    if(field.validate.includes("email")) {
      //email
      if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values[fieldName])) {
        errors[fieldName] = 'Invalid email address'
      }
    }
    
    if(field.validate.includes("minLength")) {
      //minLength
      if (values[fieldName] !== undefined && values[fieldName].length < 3) {
        errors[fieldName] = 'Must be 3 characters or more'
      }
    }

    if(field.validate.includes("required")) {
      //required
      if (!values[fieldName] && typeof values[fieldName] !== "number") {
        errors[fieldName] = 'Required'
      }
    }

I've tried to write a function that looks like this - but I don't want to break the stack.

  messageHandler(field, validation, rule, message){
    if(field.validate.includes(validation)) {
      if (rule) {
        return message;
      }
    } 
  }


from Refactoring validation handling and messaging

No comments:

Post a Comment