EternalGrey
EternalGrey

Reputation: 19

JavaScript test RegEx always returning false

I'm trying to verify if a string looks like a valid e-mail address, however the function is always returning false regardless of what I type

function looksLikeMail(str) {
      var patt = new RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);
      return patt.test(str);
    }

var c1;
var c2;
var error = false;
c1 = document.getElementById("t8").value;
c2 = document.getElementById("t9").value;
if (document.getElementById("t8").value != "" || document.getElementById("t9").value != ""){
     if (document.getElementById("t8").value != ""){
     var validE;
     validE = looksLikeMail((String)(t8));
     if (!validE){
        error = true;
        alert("invalid email address");
       }
}

HTML

<div class="form-row">
  <label class="col align-self-center">&nbsp;<b>email (at least one)</b></label>
  </div>


  <div class="form-row">
  <div class="col-md-6 offset-md-3">
  <label for="inputEmail4">email-1</label>
  <input type="email" class="form-control" id="t8" placeholder="email">
  </div>

  <div class="col-md-6 offset-md-3">
  <label for="inputEmail5">email-2</label>
  <input type="email" class="form-control" id="t9" placeholder="email">
  </div>
  </div>

Upvotes: 0

Views: 52

Answers (2)

Rolly
Rolly

Reputation: 3385

Try this code

        function looksLikeMail(str){
            var regex = /^(([^<>()\[\]\\.,;:\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 regex.test(str);
        }

        looksLikeMail("[email protected]");// true
        looksLikeMail("[email protected]");// false
        looksLikeMail("[email protected]");// true

Also you can test the regex here

https://regex101.com/r/777dwJ/1

Regex credits to. https://stackoverflow.com/a/46181/5708097

Upvotes: 0

junvar
junvar

Reputation: 11604

Your looksLikeMail is fine (returns true for '[email protected]').

The rest of your JS though seems problematic. For one, your variable t8 is never defined. Also, (String) is invalid syntax. To cast in JS, you could do String(t8) instead. That being said, this is unnecessary because input.value will return a string anyways.

Since you seem unfamiliar with JS, i've done some small cleanup as well:

let t8 = document.getElementById("t8").value;
if (t8) {
     let validE = looksLikeMail(t8);
     if (!validE){
        error = true;
        alert("invalid email address");
     }
}

Upvotes: 1

Related Questions