2

This is a part of my partial view -

<div class="form-group row">
    <label for="email" class="col-sm-2 form-control-label">Email address</label>
    <div class="col-sm-9">
        <input type="email" class="form-control" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" placeholder="Email Address" required/>
    </div>
</div>

This is a part of my controller -

var re = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/;

self.email = document.getElementById("email");

angular.element(self.email).on("input", function () {
    console.log("Inside event");
    if(self.email.value != re) {
        var closest3 = self.email.closest('div');
        closest3.className += " has-error";
    }

    else {
        closest3.className += " has-success";   
    }
});

Why is the else condition never being triggered. I am giving the input characters@characters.com

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
Aaron
  • 1,345
  • 2
  • 13
  • 32

3 Answers3

3

You're comparing the string with the regular expression, which will almost certainly always be different. You instead need to test that the regex matches:

if(!re.test(self.email.value)) {

There are a few other issues with the code as presented though. I've moved the declaration and initialisation of closest3 so that it's available in the else block correctly. You should also remove the "wrong" class in each block to ensure correct behaviour, otherwise it will end up having both classes applied. I've used the classList functionality to do so, but depending on your environment you may need to use a different method of doing so, as it's a fairly modern property (older versions of IE will fail).

var closest3 = self.email.closest('div');
if(!re.test(self.email.value)) {
    closest3.classList.remove("has-success");
    closest3.className += " has-error";
} else {
    closest3.classList.remove("has-error");
    closest3.className += " has-success";   
}
Community
  • 1
  • 1
James Thorpe
  • 31,411
  • 5
  • 72
  • 93
2

Because that is not how regular expressions work.

You want to use re.test(str) or str.match(re).

epascarello
  • 204,599
  • 20
  • 195
  • 236
2

You need to use str.match(regexp) in your if condition :

 if(!self.email.value.match(re))
R3tep
  • 12,512
  • 10
  • 48
  • 75