0

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>

2 Answers2

1

Your looksLikeMail is fine (returns true for 'a@a.com').

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");
     }
}
junvar
  • 11,151
  • 2
  • 30
  • 46
0

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("aa@aa.cc");// true
        looksLikeMail("aa@aa.c");// false
        looksLikeMail("demo_a-su@abcca.cd.bc");// true

Also you can test the regex here

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

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

Rolly
  • 3,205
  • 3
  • 26
  • 35