Today is the first time I touch the Java Script language. Since I was asked this: JS function must be created, which must receive a string . This entered string must meet the following conditions:
It should only contain alphanumeric characters. It must have a minimum length of 6 characters. It must start with an uppercase letter. It must have a maximum length of 12 characters.
However, being new to this language, I don't know if you can please advise me on the following code, since I feel that I am repeating several things. (the code in what I tested works)
//let name_user = document.getElementById("campoUsuario").value;
// se chequea el regex de que el string no tenga espacio
var espacio = /\s/;
//se chequea con el regex que no comience por números
var numero_init = /^\d/
//se chequea con el regex que solo tenga caracteres alfanumeros
var char_alpha = /^[0-9a-zA-Z]+$/
if(!espacio.test(name_user)){
if(!numero_init.test(name_user)){
if(char_alpha.test(name_user)){
let longitud = name_user.length;
if (longitud >=6 && longitud <= 8){
let letra = name_user.charAt(0)
if ( letra == letra.toUpperCase()){
return name_user;
}
else{
console.log("la primera letra no es mayuscula");
return false;
}
}
else{
console.log("la longitud no cumple");
return false;
}
}
else{
console.log("no puede tener caracteres espciales");
return false;
}
}
else{
console.log("El usuario no puede inciar con un número");
return false;
}
}
else{
console.log("La contraseña no puede contener espacios en blanco");
return false;
}
}
let name_user = "San4566"
console.log(validar_usuario(name_user)); ```
You can base everything on a single regular expression
Where:
^[A-Z]
indicate that the string must start with a capital letter\w{5,12}
consider strings of minimum length 5 and maximum 6, but each one is alphanumeric\w{5,12}$
must end with alphanumericNote
If you want to show specifically what fails you can use an array of conditions and just search if some condition is met or not.