Skip to content

Instantly share code, notes, and snippets.

@andrit
Last active October 3, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrit/645610afa00893177af98b21e9c2b213 to your computer and use it in GitHub Desktop.
Save andrit/645610afa00893177af98b21e9c2b213 to your computer and use it in GitHub Desktop.
 checkForm = ({firstname, lastname, phone, email}) => {
        const phoneRegex = /^\(?\d{3}\D*\d{3}\D*\d{4}$/; 
            const emailRegex=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            let emailInvalid = false; 
            let phoneInvalid = false;
            if(!email.match(emailRegex) ){
                emailInvalid = true;
            }
    
            if(!phone.match(phoneRegex) ){
                phoneInvalid = true;
            }
        return {
            firstname:
              !firstname || firstname.trim().length === 0
                ? "First Name is required"
                : false,
            lastname:
              !lastname || lastname.trim().length === 0
                ? "Last Name is required"
                : false,
            email:
                !email || email.trim().length === 0 || emailInvalid
                  ? "Email is required"
                  : false,
            phone:
                !phone || phone.trim().length === 0 || phoneInvalid
                  ? "Phone is required"
                  : false
          };
        }

        checkWholeForm = () => {
            return new Promise((res, rej) => {
                try {
                    let errors = this.checkForm(this.props);
                    let formValid = 0;
                    
                    for(let i in errors) {
                        if(errors[i] === false){
                            ++formValid
                        } else {
                            --formValid
                        }
                    }
                    
                    this.props.checkFormValid(formValid);
                    res();
                } catch(e){
                    rej(e)
                }
            })
           
        }
        
        //in the parent we could store validity status or put in the same component
 checkBasicFormValid = (validity) =>{
    this.setState({ basicFormValid: validity})
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment