Of course it has how to determine specific quantities.
If you want a letter followed by 7 numbers, just change the regex to:
/^[A-Za-z][0-9]{7}$/
If you want to define the minimum and maximum quantity, just change the quantifier. For example, {2,7}
for a minimum of 2 and a maximum of 7. Or {2,}
at least 2, without a ceiling.
Another detail is that the method match
returns an array containing various information, such as the snippet that was found, capture groups, etc. But if you don’t need this information and only want to know if the string corresponds to regex (ie only "yes or no"), you can use method test
, that simply returns true
or false
:
let regex = /^[A-Za-z][0-9]{7}$/;
if (regex.test(inputvalue.value)) {
// sucesso
} else {
// falha
}
And this regex can be used in the attribute pattern
hassle-free:
const campo = document.querySelector('#campo');
campo.addEventListener('input', () => {
campo.setCustomValidity('');
campo.checkValidity();
});
campo.addEventListener('invalid', () => {
campo.setCustomValidity('O campo deve ter uma letra seguida de 7 dígitos');
});
/* deixar borda vermelha enquanto o campo for inválido */
input:invalid {
border: red 1px solid;
}
<form>
<input id="campo" type="text" pattern="^[A-Za-z][0-9]{7}$" required />
<input type="submit" value="ok">
</form>
Man, I’m sorry for the mega delay! But everything went well, gave right yes ( thanks for your explanation )
– Luiz Thomaz