反应-将电子邮件验证添加到空输入验证

时间:2019-06-19 21:48:18

标签: reactjs forms email-validation

在React中,我希望将电子邮件验证(检查@和.com)添加到当前检查空输入字段的表单中。

found this可以完成工作,但是不知道如何将它与其他验证一起连接到onSubmit。

这里是link to this project's codepen,以获取完整的代码。

设置输入和错误的初始状态:

constructor() {
super();
this.state = {
  inputs: {
    name: '',
    email: '',
    message: '',
  },
  errors: {
    name: false,
    email: false,
    message: false,
  },
};

}

JS处理输入onBlur

updateInput = e => {
this.setState({
  inputs: {
    ...this.state.inputs,
    [e.target.name]: e.target.value,
  },

  errors: {
    ...this.state.errors,
    [e.target.name]: false,
  },
});
};

handleOnBlur = e => {
const { inputs } = this.state;
if (inputs[e.target.name].length === 0) {
  this.setState({
    errors: {
      ...this.state.errors,
      [e.target.name]: true,
    },
  });
}
};

2 个答案:

答案 0 :(得分:1)

无需重构太多代码,我们只需将updateInput()函数更新为:

  updateInput = event => {
    const { name, value } = event.target;

    if (name === "email") {
      this.setState({
        inputs: {
          ...this.state.inputs,
          [name]: value
        },
        errors: {
          ...this.state.errors,
          email:
            value.includes("@") &&
            value.slice(-4).includes(".com")
              ? false
              : true
        }
      });
    } else {
      this.setState({
        inputs: {
          ...this.state.inputs,
          [name]: value
        },
        errors: {
          ...this.state.errors,
          [name]: false
        }
      });
    }
  };

另请参见沙箱:https://codesandbox.io/s/conditional-display-input-errors-vfmh5

答案 1 :(得分:0)

一种可能的方法是像这样向代码添加条件

if((e.target.name === "email") && !this.validateEmail(inputs[e.target.name]) && (inputs[e.target.name].length !== 0 )   ){
     this.setState({
        errors: {
          ...this.state.errors,
          [e.target.name]: true,
        },
      }); 
    }        
 so after generally you will have something like this that add the validate function

validateEmail (email) {
    const re = /^(([^<>()\[\]\\.,;:\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,}))$/
    return re.test(email)
  } 

then your  unblur function will look like this

handleOnBlur = e => {
    const { inputs } = this.state;


     if (inputs[e.target.name].length === 0) {
       this.setState({
        errors: {
          ...this.state.errors,
          [e.target.name]: true,
        },
       });
      }
     if((e.target.name === "email") && !this.validateEmail(inputs[e.target.name]) && (inputs[e.target.name].length !== 0 )   ){
      this.setState({
        errors: {
          ...this.state.errors,
          [e.target.name]: true,
        },
      }); 
    }


  };