41

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>

       );
    }
}
Avikrit Khati
  • 861
  • 4
  • 10
  • 20

8 Answers8

109

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\w+)+$/;
  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");
  }
}
  1. You TextInput Component:
<TextInput
  placeholder="Email ID"
  onChangeText={(text) => this.validate(text)}
  value={this.state.email}
/>
MikeyE
  • 1,756
  • 1
  • 18
  • 37
Neel Gala
  • 2,350
  • 1
  • 19
  • 20
3

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 });
        }
    }
jaws
  • 1,952
  • 4
  • 20
  • 27
3

There is an easy to validate an email without writing a lot of code, by using a npm package called validator

  1. Installation
    npm i validator
    
  2. Import the package
    const validator = require('validator');
    
  3. Use it to verify the email
    validator.isEmail('john.doe@example.com');    // true
    

For more information, see the documentation: https://www.npmjs.com/package/validator

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
2

if you use hooks, you can try as this

const [email, setEmail] = useState('');
const [emailValidError, setEmailValidError] = useState('');

when user enter email this function will call

const handleValidEmail = val => {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w\w+)+$/;

if (val.length === 0) {
  setEmailValidError('email address must be enter');
} else if (reg.test(val) === false) {
  setEmailValidError('enter valid email address');
} else if (reg.test(val) === true) {
  setEmailValidError('');
}
};


 <TextInput
    style={styles.input}
    placeholder="Email"
    value={email}
    autoCorrect={false}
    autoCapitalize="none"
    onChangeText={value => {
      setEmail(value);
      handleValidEmail(value);
    }}
  />

enter this line bellow input field

{emailValidError ? <Text>{emailValidError}</Text> : null}
1

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");
}
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42
0
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
Apurva Aggarwal
  • 296
  • 3
  • 10
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.[Read this](https://stackoverflow.com/help/how-to-answer). – Shanteshwar Inde Apr 05 '19 at 08:21
0

Having a function that validates the email (probably in some separate module as you are going to reuse it),

export function validateIsEmail(email) {
  return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
}

You can validate email input,

Live validation:

        <TextInput
              ...
          onChangeText={emailText => {
            setEmail(emailText);
            setInlineValidations({
              ...inlineValidations,
              emailNotValid: !validateIsEmail(emailText),
            });
          }}
        />

In this example setEmail and setInlineValidations are state setters defined by the useState hook, example const [email, setEmail] = useState('');, you can of course adapt this to your way of handling state.

Gabriel P.
  • 3,400
  • 2
  • 32
  • 23
0
   isEmailValid = () => {
    const expression = /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([\t]*\r\n)?[\t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([\t]*\r\n)?[\t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return expression.test(String(this.state.email_id).toLowerCase())
}
patel jigar
  • 52
  • 1
  • 7