Email Validation (React Native). Returning the result as 'invalid' for all the entries

雨燕双飞 提交于 2019-12-01 03:05:51

Ok I got the code working, below you can take the look for validating the email on each user input.

  1. Your function part:

    validate = (text) => {
    console.log(text);
    let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
    if(reg.test(text) === false)
    {
    console.log("Email is Not Correct");
    this.setState({email:text})
    return false;
      }
    else {
      this.setState({email:text})
      console.log("Email is Correct");
    }
    }
    
  2. You TextInput Component:

        <TextInput
          placeholder="Email ID"
          onChangeText={(text) => this.validate(text)}
          value={this.state.email}
        />
    

Looks like a syntax error. You've got a nested function called validate directly inside the definition for go.

As a general rule I would suggest to keep your indentation and curly-brackets consistent so these sort of errors are detectable at a glance-- when the brackets don't line up there's a problem.

Then, there's a few things you might do to get this code working:

  • Remove the validate (email) line along with its accompanying close bracket
  • Reference email via this.state.email in go
  • Add an additional state variable to indicate if the email has been validated or not.

Something like:

this.state = {
 email :'',
 validated : false,
}

And...

go = () => {  
        if (this.state.email.test(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)==0) {
            this.setState({ validated : true });
        } else {
            this.setState({ validated : false });
        }
    }
validate = (text) => {
console.log(text);
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
if(reg.test(text) === false)
{
alert("Email is Not Correct");
this.setState({email:text})
return false;
  }
else {
  this.setState({email:text})
  alert("Email is Correct");
}
}


You can put this function validate in onChangeText propert of TextInput

I've created a Helper class and doing like this:

export default class Helper {

     static isEmailValid(email) {
        let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        return reg.test(email) == 0;
   }
}

Call this method by:

if (Helper.isEmailValid(this.state.emailText)) {
    console.log("Email is correct");
} else {
    console.log("Email is not correct");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!