I have a numeric input, and I would like it to be valid only in the pattern, values with .xx (dot plus two decimal places).
My code:
<div>
<label for="valorTr> Valor: </label>
<input type="number" pattern=" " id="valorTransf" />
</div>
I have a numeric input, and I would like it to be valid only in the pattern, values with .xx (dot plus two decimal places).
My code:
<div>
<label for="valorTr> Valor: </label>
<input type="number" pattern=" " id="valorTransf" />
</div>
The pattern
attribute only works on types
: text
, search
, tel
, url
, email
, or password
. It does not work in type="number"
. ( See MDN documentation )
To validate the field using regex, you can do via JavaScript using match
:
$("#valorTransf").blur(function(){
var valor = $(this).val();
if(valor.match(/^\.\d{2}\b/)){
console.log("ok");
}else{
console.log("inválido");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><labelfor="valorTr"> Valor: </label>
<input type="number" id="valorTransf" />
Where to regex:
^\.\d{2}\b/
^\. -> deverá iniciar com um ponto
\d{2} -> deverá ter 2 dígitos após o ponto
\b -> metacharacter que delimita o início (ou fim).
Significa que não pode ter mais que 2 dígitos após o ponto