Aaron Aaron - 6 months ago 11
Javascript Question

Else condition never being triggered

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

Answer

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";   
}