Set as Pattern values with two decimal places in input Html5

Asked

Viewed 751 times

1

I have a numerical input, and I would like it to be valid only by Pattern, values with . xx (point plus two decimal places).

My code:

<div>
    <label for="valorTr> Valor: </label>
    <input type="number" pattern=" " id="valorTransf" />

</div>

1 answer

1


The attribute pattern only works in types: text, search, tel, url, email, or password. Does not work in type="number". (See MDN documentation)

To validate the field using regex, you can do it 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>
<label for="valorTr"> Valor: </label>
<input type="number" id="valorTransf" />

Where the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.