I am trying to validate a users email, by checking it against an expression. But the result i am getting is invalid for all the entries.
UPDATED CODE
class dummytest extends Component{
constructor(props){
super(props);
this.state = {
email :'',
validated: false ,
}
};
go = () => {
const reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(this.state.email) === true){
alert( valid);
}
else{
alert();
}
}
render(){
return(
<View style={{alignSelf:'center',marginTop:100}}>
<TextInput autoCapitalize="none" autoCorrect={false} style={{height:20,width:200,backgroundColor:'blue'}} value={this.setState.email}/>
<Button onPress={this.go.bind(this)}>
<Text> GO </Text>
</Button>
</View>
);
}
}
Ok I got the code working, below you can take the look for validating the email on each user input.
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"); } }
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");
}
来源:https://stackoverflow.com/questions/43676695/email-validation-react-native-returning-the-result-as-invalid-for-all-the-e