You can use the attribute pattern
and required
(both HTML5). The required
will prevent the submission of the form if nothing is entered in the field, and the pattern
will prevent sending the form if the value does not follow the standard of the specified regular expression.
From what I understood, the format would be 2 numbers + 2 numbers + 2 lower case letters, separated by hyphen. The regular expression would be:
\d{2}-\d{2}-[a-z]{2}
Would look like this:
<form>
<input type="text" pattern="\d{2}-\d{2}-[a-z]{2}" required>
<br>
<button>Enviar</button>
</form>
Although the regex no pattern
requires that the value of the field is in the
specified format, Submit accepts the empty field, so it is
necessary the required
also.
Validating with Javascript
Another way is to check the field with Javascript, without using HTML5 attributes. The logic is basically the same, just check if the field value meets the regular expression. In this case, the delimiters must be included in the regex ^
(string start) and $
(string end), otherwise it would accept something like 11-22-aas
or 111-22-aa
:
document.addEventListener("DOMContentLoaded", function(){
document.forms[0].onsubmit = function(e){
var campo = document.forms[0].registro.value;
if(!/^\d{2}-\d{2}-[a-z]{2}$/.test(campo)){
e.preventDefault(); // aborta o submit
alert("Valor inválido");
}
}
});
<form>
<input type="text" name="registro">
<br>
<button>Enviar</button>
</form>
The element
<input>
has the attributepattern
that you can enter a regular expression to validate the field value. Want to try?– Woss
Check out this link, here’s what you’re looking for: https://answall.com/questions/182118/como-usar-o-attribute-pattern
– LeAndrade