反应-将电子邮件验证添加到空输入验证 [英] React - adding email validation to empty input validation

查看:92
本文介绍了反应-将电子邮件验证添加到空输入验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In React, I'm looking to add email validation (checks for @ and .com) to a form that currently checks for empty input fields.

I <一个href = https://codepen.io/cesarwbr/pen/vKqxpZ rel = nofollow noreferrer>找到了这个,它可以完成工作,但不知道如何将它与w /上的onSubmit连接我的其他验证。

I found this that does the job but can't figure out how to connect it to onSubmit along w/ my other validation.

这是链接到此项目的代码库以获取完整代码。

Here's the link to this project's codepen for complete code.

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

Setting initial State for inputs and errors:

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

}

JS处理输入,onBlur

JS Handling Input, 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()函数更新为:

Without refactoring too much of your code, we can just update the updateInput() function to this:

  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

这篇关于反应-将电子邮件验证添加到空输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆