首页 > 解决方案 > How can I optimize my validation code in reactjs?

问题描述

Below, I have mentioned my JS code. So, Kindly suggest or guide me that there is any better approach to implement the validation on form submit for react project or is it right approach which i have implemented already?

submitUserForm = (e) => {        
    e.preventDefault();        
    const { formError } = this.state;
    let valid = true;
    if(document.getElementById('useremail').value === "") {
        valid = false;
        formError.email = "Kindly enter your email id"            
    }
    else {
        valid = true;
        formError.email = ""            
    }
    if(document.getElementById('userpassword').value === "") {
        valid = false;
        formError.password = "Kindly enter the password"           
    }
    else {
        valid = true;
        formError.password = ""            
    }         
    if(valid === true) {        
        this.formSubmitApi();         
    }     
    this.setState({
        isValid: valid,
        formError
    })       
}

标签: javascriptreactjsecmascript-6

解决方案


这是改进代码的方法:

    submitUserForm = (e) => {        
            e.preventDefault();        
            const formError = {}
           if(document.getElementById('useremail').value === "") {
                formError.email = "Kindly enter your email id"            
           }
          if(document.getElementById('userpassword').value === "") {
               formError.password = "Kindly enter the password"           
           }
          Object.keys(formError).length === 0 && this.formSubmitApi(); 
           this.setState({
             formError
            })       
        }

推荐阅读