Validare uno username è un'operazione alquanto semplice con JavaScript: quello che dobbiamo verificare è l'assenza di determinati caratteri non ammessi e la lunghezza dello username. Vediamo come fare.
Possiamo utilizzare le espressioni regolari e la proprietà length
delle stringhe per il nostro scopo:
'use strict';
const Validator = {
rules: {
username: /^\w+$/,
length: 8
},
validate: user => {
let value = user.value;
if (!this.rules.username.test(value) || value.length < this.rules.length) {
return false;
}
return true;
},
init: () => {
document.querySelector('#form').addEventListener('submit', e => {
e.preventDefault();
let isValid = Validator.validate(document.querySelector('#username'));
if(!isValid) {
//...
}
}, false);
}
};
Validator.init();