简体   繁体   English

如何在reactjs中优化验证代码?

[英]How can I optimize my validation code in reactjs?

Below, I have mentioned my JS code. 下面,我提到了我的JS代码。 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? 因此,请建议或指导我,有什么更好的方法可以在对React项目的表单提交中实施验证,还是我已经实施的正确方法?

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

This is how you can improve your code: 这是改善代码的方法:

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

I would change 2 things: 我将更改2件事:

  1. Make the inputs controlled, so that you have better and direct control of the input. 使输入受到控制,以便更好,直接地控制输入。 Accessing the inputs with document.getElementById is bad practice. 使用document.getElementById访问输入是不好的做法。 Save the text of each input within the state or use refs. 将每个输入的文本保存在状态内或使用引用。
  2. I would change the check for valid input into something like this: 我会将有效输入的检查更改为如下所示:

    const errors = {}; const errors = {};

    errors.email = "Kindly enter your email id" errors.email =“请输入您的电子邮件ID”

    if (Object.keys(errors).length === 0) {...} 如果(Object.keys(errors).length === 0){...}

It should be a new object, so that you don't mutate the state and this makes it easier because you don't have a second variable. 它应该是一个新对象,这样您就不会更改状态,并且因为没有第二个变量,因此更容易实现。

I hope this helps. 我希望这有帮助。 Happy coding. 快乐的编码。

First of all, in order to improve your code, you need to have controlled components (Inputs in this case) in order to store your values in the state and then use them in the submitUserForm function, also, instead of valid variable, I'll use a validation function like (Also, make the useremail and userpassword objects, in order to store the errors there): 首先,为了改进您的代码,您需要具有受控组件(在这种情况下为Inputs),以便将值存储在state ,然后在submitUserForm函数中使用它们,而不是valid变量,我将ll使用类似的验证功能(另外,使useremailuserpassword对象,以便在其中存储错误):

state = {
    useremail: { value: '', error: '' },
    userpassword: { value: '', error: '' },
};

validateValue = value => {
    return value !== undefined && value !== null && value !== '';
};

submitUserForm = e => {
    const { useremail, userpassword } = this.state;

    e.preventDefault();

    // If both the 'useremail' and the 'userpassword' pass the 'validateValue' validations, then send the data
    if (this.validateValue(useremail.value) && this.validateValue(userpassword.value)) {
        this.formSubmitApi(useremail.value, userpassword.value);

        // After sending the info, we reset our two states to initial state
        this.setState({useremail: { value: '', error: '' }, userpassword: { value: '', error: '' } });
    } else {
        // If 'useremail' don't pass the validation we store the error
        if (!this.validateValue(useremail.value)) {
            this.setState({ useremail: { value: useremail.value, error: 'Please enter a valid email' }});
        }

        // If 'userpassword' don't pass the validation we store the error
        if (!this.validateValue(userpassword.value)) {
            this.setState({ userpassword: { value: userpassword.value, error: 'Please enter a valid password' }});
        } 
    }
};

I think this is a more clean approach, you only have to states instead of three as before and you can get all the information that you need from those states. 我认为这是一种更干净的方法,您只需声明状态即可,而不必像以前那样声明三个状态,并且可以从这些状态中获得所需的所有信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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