I need help with creating a regex to: at least 1 number, only letters in English, at least one special char (@!#$%^&*()- _), no spaces and not 3 same letters in a row.
ty!
function passwordValidated() {
var password = document.getElementById("password").value;
var passMsg = document.getElementById("passMsg");
if (password.length > 6 && password.length > 12) {
passMsg.innerHTML = "password must contain above 6 charcters and below 12";
return false;
}
var specialChar = /[@!#$%^&*()- _]/;
if (!specialChar.test(password)) {
passMsg.innerHTML = "password must contain a special character";
return false;
}
var numberCheck = /(?=\S* [\d])/;
if (!numberCheck.test(password)) {
passMsg.innerHTML = "password must contain at least one number";
return false;
}
passMsg.innerHTML = "";
return true;
}
this is my code for now.
CodePudding user response:
const validators: ((s: string) => true | string)[] = [
s => s.length >= 6 || "password must contain above 6 charcters and below 12",
s => s.length <= 12 || "password must contain above 6 charcters and below 12",
s => /[@!#$%^&*()- _]/.test(s) || "password must contain a special character",
s => /\d/.test(s) || "password must contain at least one number",
s => !/(.)\1\1/.test(s) || "not 3 same letters in a row",
s => !/\s/.test(s) || "no spaces please",
s => /^[@!#$%^&*()- _\w] $/.test(s) || "only letters in English"
]
function validate (value: string, validators: ((s: string) => true | string)[]) {
for (let v of validators) {
let r = v(value);
if (r !== true) return r;
}
return true;
}
console.log([
validate('asd', validators),
validate('asdhakufhskuydgsiyug', validators),
validate('asdj$hgsd', validators),
validate('asdj$4h gsd', validators),
validate('asdj$4hgsd', validators),
])
Inspired by Quasar (Vue framework) imput field validation