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

React - adding email validation to empty input 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,
    },
  });
}
};

无需重构太多代码,我们只需将 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

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

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


  };