I want to display various messages with the customValidity() to show that it fails the user. I have this but I think the expresión regular
.
window.addEventListener("load", function() {
let usuario = false;
let contra = false;
document.querySelector("#pass").addEventListener("input", function() {
contra = pass();
});
document.querySelector("#submit").addEventListener("click", function(e) {
if (document.forms[0].checkValidity()) {
e.preventDefault();
if (contra) {
console.log("valida");
}
}
});
function pass() {
let cont = 0;
let pass = document.querySelector("#pass");
let regex = {
".{8,20}": "El nombre de usuario tiene que tener un mínimo de 8 caracteres",
"(?=.*\d)(?=.*[a-zA-Z])(?=.*[@#$%&_])": "El nombre de usuario debe contener un dígito, una letra y uno de los siguientes caracteres especiales (@#$%&_)",
};
if (pass.value == "")
pass.setCustomValidity("Completa este campo");
else {
for (let i in regex) {
let reg = new RegExp(i, "g");
let valida = reg.test(pass.value);
if (valida === false) {
cont++;
pass.setCustomValidity(regex[i]);
break;
}
pass.setCustomValidity("");
}
}
if (cont == 0)
return true;
else
return false;
}
});
body {
margin-left: 1em;
}
div {
margin-bottom: 1.1em;
}
input {
font-size: 100%;
width: 210px;
box-sizing: border-box;
padding: .2em;
}
button {
width: 120px;
box-sizing: border-box;
}
.titulos {
display: block;
margin: .5em 0 .4em 0;
font-weight: bolder;
color: grey;
}
<form action="">
<div>
<label for="pass" class="titulos">Contraseña</label>
<input type="password" id="pass" required>
</div>
<button type="submit" id="submit">Registro</button>
</form>
How would they be made expresiones regulares
to display a message in each case?
You have two small problems.
The first is that the second regular expression is using
\d
, which would be valid on a regular expression object. But this is not your case: you are really handling a string that you then use to build a regular expression. And in the strings the counterslashes have to be escaped with another counterslash\\
. So in your string you should use\\d
or some alternative like[0-9]
Once fixed, the first regular expression doesn't quite work very well because it allows texts with more than 20 positions. This is because you don't say where it should start counting from. So even in a text of 1000 characters there is always a part where you can find between 8 and 20 characters.
Yours would be to use start and end of line like:
^.{8,20}$
In the second regular expression it is not necessary, because all you are interested in is finding certain characters.
Finally, I would disable the global "g" modifier since you don't want to do multiple searches on the same text, but rather check if it matches your regular expression.
After the changes it would look like this: