I need to check that a value(key) has:
- Minimum 8 characters.
- Upper case and lower case.
- Numbers.
- It can contain
!
or?
, but no other special characters.
So far I have the following:
function enRango(x, min, max) {
return ((x - min) * (x - max) <= 0);
}
const clave = document.getElementById('clave');
function comprobarContraseña(clave) {
let resul = 0;
for (let i = 0; i < clave.length; i++) {
if (!enRango(clave.charCodeAt(i), 34, 47) || !enRango(clave.charCodeAt(i), 58, 62)) {
if (minusculas.test(clave)) {
if (numeros.test(clave)) {
resul = 1;
console.log('has entrado hasta el final');
return resul;
}
}
} else {
resul = 1;
return resul;
}
if (minusculas.test(clave) && numeros.test(clave)) {
console.log('estas en el minusculas y numeros');
return resul;
}
}
}
minusculas
and numeros
they are two regular expressions that I have created, but since I do not have much knowledge in the matter, I think that I have some mistake when checking.
const minusculas = new RegExp('^[a-z]+$');
const numeros = new RegExp('^[0-9]+$');
I think everything can be checked directly with a Regular Expression but I don't know exactly how to do it.
You must do the validations one by one, for this I recommend you guide yourself from the regular expressions reference .
It's not that in theory you can't do it in a single regular expression, but it will be much more complex.
To join all the validations use the logical operator
&&
.There are two ways to define a regular expression in javascript, the one you put where you have to escape the characters and the already escaped way, where you put your regular expression between slashes (
/
)To verify if a validation is fulfilled with some text to your regular expression, you call its method
test
and its parameter must be a string.In the end you will have something like this: