简体   繁体   English

反应中的即时输入字段验证

[英]Instant input field validation in react

I have some input field in React, I want to do the instant validation for them:我在 React 中有一些输入字段,我想对它们进行即时验证:

  1. Validate the Email Address is in the correct format.验证 Email 地址格式是否正确。 if not, show the error right next to the Email Address input field.如果没有,请在 Email 地址输入字段旁边显示错误。

  2. Validate Email Address and Verify Email Address match.验证 Email 地址并验证 Email 地址匹配。 if not, show the error right next to the Verify Email Address input field.如果不是,请在“验证 Email 地址”输入字段旁边显示错误。

  3. Validate that Name is not blank.验证名称不为空。

export default class DOB extends Component {
constructor() {
  super();
  this.state = {
    Year: "",
    Month: "",
    Day: "",
    YearFocused: false,
    MonthFocused: false,
    DayFocused: false,
    Valid: true
  };
}

render() {
  return (
    <div>
      <p>
        Email Address:
        <input type="text" value="" />
      </p>
      <p>
        Verify Email Address:
        <input type="text" value="" />
      </p>
      <p>
        Name:
        <input type="text" value="" />
      </p>
      <p>
        DOB (YYYY MM DD):
        <input className="Year" type="text" />
        <input className="Month" type="text" />
        <input className="Day" type="text" />
      </p>
      <p>
        <button>Submit</button>
      </p>
    </div>
  );
}
}

You could create a handle function that will deal with field changes and then you can manage your validations.您可以创建一个句柄 function 来处理字段更改,然后您可以管理您的验证。 Here's a quick example done with the Email and Verify Email fields .这是使用 Email 和验证 Email 字段完成的快速示例 You can follow the same approach for the field "name".您可以对字段“名称”采用相同的方法。

Also, take a look at the Controlled Components docs.另外,请查看受控组件文档。 It will guide you to understand better how this can be done.它将指导您更好地了解如何做到这一点。 As soon as you understand well you could look for a helper library, like formik .一旦你理解得很好,你就可以寻找一个帮助库,比如formik

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

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