Reputation: 77
I've got a classic input validation for an email and a password, but for some reason my logic doesn't work and I can't figure out the part where it fails. This is code I've refactored from some one else and it bugging me quite a lot now
function Validation() {
this.regex = {
email: new RegExp(/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9-]+/),
password: new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,13}/),
},
this.email = function () {
let valElement = document.getElementById("mail");
console.log(valElement);
let valueR = valElement.value.toString();
console.log(valueR);
let erorrEl = document.getElementById("error");
let validate_mail = valueR.length == 0 && this.regex.email.test(valueR);
console.log(validate_mail);
console.log(this.regex.email);
if(!validate_mail){
valElement.className = "invalid";
erorrEl.innerHTML = "Please enter a correct email";
erorrEl.className = "error active"
console.log("not validated email");
event.preventDefault();
}else{
valElement.className = "valid";
erorrEl.innerHTML = "";
erorrEl.className = "error"
console.log("validated email");
}
}
this.password = function () {
let valElement = document.getElementById("pass");
let valueR = valElement.value;
let erorrEl = document.getElementById("error2");
let validate_pass = valueR.length == 0 && this.regex.password.test(valueR);
if(!validate_pass){
valElement.className = "invalid";
erorrEl.innerHTML = "Please enter a correct password";
erorrEl.className = "error active"
console.log("not validated password");
event.preventDefault();
}else{
valElement.className = "valid";
erorrEl.innerHTML = "";
erorrEl.className = "error"
console.log("validated password");
}
}
this.form = function(){
if(this.password && this.email){
}else{
}
}
}
var Valdator = new Validation();
Valdator.email();
Valdator.password();
Usually I'm calling these Valdator email and password functions in another file where it's a request from an API, but the idea is the same here, I don't think that woould make a difference
Upvotes: 0
Views: 51
Reputation: 7521
Your RegEx is never being executed because valueR.length == 0
will evaluate to false
, which short-circuits your &&
before it can execute the second part. Remember that if you are AND-ing two statements and the first statements evaluates to false
, there is no need to evaluate the second statement because both false && true
and false && false
evaluate to false
.
That being said, it makes no sense to check for valueR.length == 0
as a pre-condition for evaluating a RegEx on valueR
- why would we run an RegEx on a 0-length string? You should flip this logic to !==
.
And please always use ===
or !==
in the future, as ==
gets messy with type conversion.
let validate_pass = valueR.length !== 0 && this.regex.password.test(valueR);
Upvotes: 2