How do I mask an input?

Asked

Viewed 40,270 times

6

I’m trying to put on a mask CPF in a input, I’ve seen a lot of answers here and none of them worked, I tried to use the mask on its own input, in the jQuery and none of it worked.

I use the Framework Materialize. Is that what is returning this error?

  • 1

    Share with us what you’ve been trying

2 answers

24

You can also do it with pure Javascript!

<!DOCTYPE html>
<html>
	<head>
		<title>Máscara CPF</title>
		<script type="text/javascript">
			function fMasc(objeto,mascara) {
				obj=objeto
				masc=mascara
				setTimeout("fMascEx()",1)
			}
			function fMascEx() {
				obj.value=masc(obj.value)
			}
			function mTel(tel) {
				tel=tel.replace(/\D/g,"")
				tel=tel.replace(/^(\d)/,"($1")
				tel=tel.replace(/(.{3})(\d)/,"$1)$2")
				if(tel.length == 9) {
					tel=tel.replace(/(.{1})$/,"-$1")
				} else if (tel.length == 10) {
					tel=tel.replace(/(.{2})$/,"-$1")
				} else if (tel.length == 11) {
					tel=tel.replace(/(.{3})$/,"-$1")
				} else if (tel.length == 12) {
					tel=tel.replace(/(.{4})$/,"-$1")
				} else if (tel.length > 12) {
					tel=tel.replace(/(.{4})$/,"-$1")
				}
				return tel;
			}
			function mCNPJ(cnpj){
				cnpj=cnpj.replace(/\D/g,"")
				cnpj=cnpj.replace(/^(\d{2})(\d)/,"$1.$2")
				cnpj=cnpj.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")
				cnpj=cnpj.replace(/\.(\d{3})(\d)/,".$1/$2")
				cnpj=cnpj.replace(/(\d{4})(\d)/,"$1-$2")
				return cnpj
			}
			function mCPF(cpf){
				cpf=cpf.replace(/\D/g,"")
				cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
				cpf=cpf.replace(/(\d{3})(\d)/,"$1.$2")
				cpf=cpf.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
				return cpf
			}
			function mCEP(cep){
				cep=cep.replace(/\D/g,"")
				cep=cep.replace(/^(\d{2})(\d)/,"$1.$2")
				cep=cep.replace(/\.(\d{3})(\d)/,".$1-$2")
				return cep
			}
			function mNum(num){
				num=num.replace(/\D/g,"")
				return num
			}
		</script>
	</head>
	<body>

		<input type="text" name="cpf" onkeydown="javascript: fMasc( this, mCPF );">

	</body>
</html>

I already left some masks ready: CNPJ, zip code, phone and only numbers.

These masks were developed based on regular expressions. It is worth studying on the subject.

  • 2

    Perfect friend. The advantage of this mask is that it can be used in validations via AJAX/SQL because it is not submitted, contrary to Jquery Mask.

9

You can use the jQuery Mask: https://igorescobar.github.io/jQuery-Mask-Plugin/

With it you can apply various types of mask.

Suffice link the library in your html: https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.min.js

To CPF you must do it this way:

$('.cpf').mask('000.000.000-00', {reverse: true});

Browser other questions tagged

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