Brijesh Patel
Brijesh Patel

Reputation: 157

React JS : Check Email Id is valid or not along with comma separated email id

I have input field which have prefilled email Id. I can change its value to one valid email id or multiple emailIds using comma separated. I am facing one issue is that it is not validating that the email id is valid or not. no matter it is one email id or multiple email id using comma separated

Below is the code that I have tried.

import React, {Component } from 'react'

class Email extends React.Component{

 sendContactEmailId
 getCommaSeparateValue

  constructor(props){
    super(props);

    this.state = {
      emailValue : "[email protected]",
      error:''
    }
  }

  checkEmailInput = (value) => {
    const regEx = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var result = value.replace(/\s/g, "").split(/,|;/);        

    for(var i = 0;i < result.length;i++) {
        
        if(!regEx.test(result[i])) {
            this.setState({
                error : 1,  
            })
        }

        this.setState({
            error : 0,
            emailValue : value,
        })
    } 

if(this.state.emailValue.indexOf(',') > -1){

        let getEmailId = this.state.emailValue.substr(0, this.state.emailValue.indexOf(','));

        this.sendContactEmailId = getEmailId,
        this.getCommaSeparateValue = this.state.emailValue.substr(this.state.emailValue.indexOf(",") + 1)
    
        console.log("Send Contact Email : " , this.sendContactEmailId)
        console.log("Get Comma Separate Value : " , this.getCommaSeparateValue);

        this.arrayOfString = this.getCommaSeparateValue.split(',');
        console.log("Array of String: " , this.arrayOfString);

    }      
}

changeValue = (value) => {
  this.setState({
    emailValue: value
});
}
  render(){
    return(
      <div>
        <input type="text" value={this.state.emailValue} 
          onBlur={(e) => this.checkEmailInput(e.target.value)}  onChange={e => this.changeValue(e.target.value)}
          
        />
        {
            this.state.error === 1 ?

            <span>Invalid Email</span> : ''
          }
      </div>
    )
  }
}


export default Email

Any help would be great.

thank you.

Upvotes: 0

Views: 2641

Answers (2)

Amarnathrao Sulake
Amarnathrao Sulake

Reputation: 481

If input param is "[email protected],[email protected],c@123";

In order to validate email, first split with ',' and then validate the list of emails using isEmailsValid function.

const input = "[email protected],[email protected],c@123";

const emailList = input.split(',');

const emailValidationResult = isEmailsValid(emailList);

/* 
* if result is true then the list of emails are valid
* else list of emails are not valid
*/


// Function to validate list of emails by iterating through the list.
isEmailsValid = (emailList) => {
    for(let i=0; i<emailList.length; i+=1){
        const regEx = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        if(!regEx.test(email)){
            return false;
        }
    }
    return true;
}

Upvotes: 0

dance2die
dance2die

Reputation: 36925

You are setting error to 0 everytime in the validation for loop.

You need to check for else case when setting error value to 0.
(Meaning, you need turn off the error only if regEx.test passes.)

for (var i = 0; i < result.length; i++) {
  if (!regEx.test(result[i])) {
    this.setState({
      error: 1
    });
  } else {
    this.setState({
      error: 0,
      emailValue: value
    });
  }
}

And also, I'd recommend you to put the positive test case in the if as it makes the code more readable and causes less cognitive load.

  // Check for positive instead of negative.
  // It improves the readability and
  // put less cognitive load.
  if (regEx.test(result[i])) {
    this.setState({
      error: 0,
      emailValue: value
    });
  } else {
    this.setState({
      error: 1
    });
  }
}

Working demo
Edit 0oo99yjj3l


To answer the comment,

You can simply split the string and filter out empty records.
You need filter to get rid of empty strings (refer to the demo below).

Run the code snippet to see it work.

let result = "[email protected], ".split(",").map(email => email.trim()).filter(email => email);
console.log(result);

result = "[email protected], ".split(",").map(email => email.trim());
console.log(`result without filter`, result);

result = "[email protected], [email protected]".split(",").map(email => email.trim()).filter(email => email);
console.log(result);

Upvotes: 1

Related Questions