简体   繁体   English

如何在 React Native 中验证 TextInput 值?

[英]How to validate TextInput values in react native?

for example, While entering an email in the TextInput, it should validate and display the error message.例如,在 TextInput 中输入电子邮件时,它应该验证并显示错误消息。 where the entered email is valid or not输入的电子邮件是否有效

在此处输入图片说明

You can use a regex to check if the mail entered is valid.您可以使用正则表达式来检查输入的邮件是否有效。

Regex function正则函数

validateEmail = (email) => {
  var 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);
};

Submit text input function提交文字输入功能

onSubmit = () => {
if (!this.validateEmail(this.state.text_input_email)) {
  // not a valid email
} else {
  // valid email
}

You can validate your input value using onBlur event on TextInput You can apply your regex or check conditions on this event.您可以使用TextInput上的onBlur事件验证您的输入值您可以在此事件上应用正则表达式或检查条件。

Like this:像这样:

<TextInput
      onBlur= () => {
        //Conditions or Regex
      }
/>

In your case, Regex function:在您的情况下,正则表达式功能:

validateEmail = (email) => {
var 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);
};

Text Input Code:文本输入代码:

<TextInput
  onBlur= () => {
    if (!this.validateEmail(this.state.text_input_email)) {
       // not a valid email
    } else {
       // valid email
    }
  }
/>

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

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