How to Make a Field Mask in HTML with Pure Javascript?

Asked

Viewed 104 times

-1

I was developing a simple project, and I needed to use masks in a certain form. I opted, at that time, for the use of JQuery with the library Jquery Mask Plugin.

$(document).ready(function(){
  $('.dinheiro').mask('000.000.000,00', {reverse: true});
});

But Jquery is conflicting with Angular when manipulating DOM, so I had to remove Jquery from dependencies.

How can I implement a mask with pure Javascript?

  • 1

    In addition to the native implementation, an alternative would be the ngx-Mask

  • 1

    Here: https://answall.com/questions/241620/formatar-valor-em-dinheiro-enquanto-digita-com-javascript-puro

  • @renanzin worked, but I still want to know what happens "underneath the scenes" in a mask

  • Obs: This Mask is very bad, besides that it doesn’t work very well for mobile...

  • to avoid conflicts, use: jQuery.noConflict();

1 answer

0


I used the regex that was in an answer here, in the link the user who responded also explains the regular expression.

function validaCampo(c) {
      let valor = c.value;
      
      if(/([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/.test(valor)) {
        c.style.backgroundColor = "green"; 
         } else {
        c.style.backgroundColor = "red";
      }
}
* {
  margin: 0;
  box-sizing: border-box;
}

.validable-field {
  display: block;
  width: 180px;
  margin: auto;
  margin-top: 5%;
}
<input class="validable-field" type="text" onBlur="validaCampo(this)" placeholder="Exemplo: 000.000.000-00">

<input class="validable-field" type="text" onBlur="validaCampo(this)" placeholder="Click para dar onBlur">

Browser other questions tagged

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