Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. where the entered email is valid or not

enter image description here

like image 989
Karthick Kumar Avatar asked Mar 22 '16 06:03

Karthick Kumar


People also ask

How validate email in TextInput React Native?

How Do I Validate Email in React Native? The easiest way to do email validation in React Native is to create a simple email input form using the Native Components TextInput component. The TextInput accepts user input, which can then be stored in state as an email address.

How do you check if TextInput is empty React Native?

To check if an input is empty in React:Call the trim() method on the field's value. Access the length property on the value. If the field's value has a length of 0 , then it is empty, otherwise it isn't.


2 Answers

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
}
like image 99
G. Hamaide Avatar answered Oct 19 '22 10:10

G. Hamaide


You can validate your input value using onBlur event on TextInput You can apply your regex or check conditions on this event.

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
    }
  }
/>
like image 45
harshit raghav Avatar answered Oct 19 '22 10:10

harshit raghav