Error formatting zip code

3

I'm having problems with my script, when the Zip Code field is already formatted, it clears the field by clicking the button again. How do I not accuse it as an invalid format or not clean the field when it is already formatted?

Script

window.onload=function(){
	document.getElementById("botao").onclick=function(){
		var strCEP = document.getElementById("cep").value;

		cep.value = formatarCEP(strCEP);
	}
}

function formatarCEP(str){
	var re = /^([\d]{2})([\d]{3})([\d]{3})|^[\d]{2}.[\d]{3}-[\d]{3}/;

	if(re.test(str)){
		return str.replace(re,"$1.$2-$3");
	}else{
		alert("CEP inválido!");
	}
	
	return "";
}
<!DOCTYPE html>
<html lang="pt-BR">
	<head>
		<meta charset="utf-8"/>
		<title>Página Teste</title>
		<script type="text/javascript" src="js/script.js"></script>
	</head>
	<body>
		<div>
			<label for="cep">CEP: <input type="text" id="cep" maxlength="8" /></label>
		</div>
		<p>
			<button id="botao">Testar</button>
		</p>
	</body>
</html>
    
asked by anonymous 13.11.2015 / 00:02

3 answers

5

The problem is with your RegEx:

/^([\d]{2})([\d]{3})([\d]{3})|^[\d]{2}.[\d]{3}-[\d]{3}/

When there are only digits, the capture groups $ 1, $ 2, and $ 3 are caught by the parentheses, in the condition before | :

/^([\d]{2})([\d]{3})([\d]{3})/
     $1       $2       $3

However, with the formatted number, you fall into this part of RegEx:

/^[\d]{2}.[\d]{3}-[\d]{3}/

that has no group, so $ 1, $ 2 and $ 2 are empty.

Taking both conditions, I merged into one, making the dot and dash optional through the * operator. See below:

window.onload=function(){
	document.getElementById("botao").onclick=function(){
		var strCEP = document.getElementById("cep").value;

		cep.value = formatarCEP(strCEP);
	}
}

function formatarCEP(str){
	var re = /^([\d]{2})\.*([\d]{3})-*([\d]{3})/; // Pode usar ? no lugar do *

	if(re.test(str)){
		return str.replace(re,"$1.$2-$3");
	}else{
		alert("CEP inválido!");
	}
	
	return "";
}
<!DOCTYPE html>
<html lang="pt-BR">
	<head>
		<meta charset="utf-8"/>
		<title>Página Teste</title>
		<script type="text/javascript" src="js/script.js"></script>
	</head>
	<body>
		<div>
			<label for="cep">CEP: <input type="text" id="cep" maxlength="8" /></label>
		</div>
		<p>
			<button id="botao">Testar</button>
		</p>
	</body>
</html>

Note that this use of RegEx is very limited. I would probably in your place work on these points:

  • Accept more characters in the field, easing the user's life by using copy & paste , which often comes with extra spaces, and improper characters.

  • Discard any non-digit character, since it will be formatted anyway.

  • I would not use RegEx. RegEx is a feature that is used when simpler solutions do not solve. In your case, it can be resolved with string operations.

  • 13.11.2015 / 00:43
    2

    Change the regular expression to this form:

    /^([\d]{2})\.?([\d]{3})\-?([\d]{3})/
    

    Where is the metacharacter? indicates in this expression that the existence of the characters. and - are not required for validation of the same, but are optional, with occurrence of zero or one character.

    You could also use it below with the metacharacter *, it would work, but it would have a small error, where CEP's such as that 11 ... 000 --- 000 will also be valid, since the metacharacter quantifier * checks to be the String has the occurrence of zero more characters.

    In your code snippet, do not be aware of this error because of the input text limitation.

    /^([\d]{2})\.*([\d]{3})\-*([\d]{3})/
    

    window.onload=function(){
    	document.getElementById("botao").onclick=function(){
    		var strCEP = document.getElementById("cep").value;
    
    		cep.value = formatarCEP(strCEP);
    	}
    }
    
    function formatarCEP(str){
    	var re = /^([\d]{2})\.?([\d]{3})\-?([\d]{3})/;
    
    	if(re.test(str)){
    		return str.replace(re,"$1.$2-$3");
    	}else{
    		alert("CEP inválido!");
    	}
    	
    	return '';
    }
    <!DOCTYPE html>
    <html lang="pt-BR">
    	<head>
    		<meta charset="utf-8"/>
    		<title>Página Teste</title>
    		<script type="text/javascript" src="js/script.js"></script>
    	</head>
    	<body>
    		<div>
    			<label for="cep">CEP: <input type="text" id="cep" maxlength="8" /></label>
    		</div>
    		<p>
    			<button id="botao">Testar</button>
    		</p>
    	</body>
    </html>
        
    13.11.2015 / 00:52
    1

    follows the validation of the zip in JQUERY

    ---------- HTML

    <div>
                <label for="cep">CEP: <input type="text" id="cep" ></label>
            </div>
            <p>
                <button id="botao">Testar</button>
            </p>
    

    ------------ SCRIPT

    function validarCep()
    {
        var patt = new RegExp(/^([\d]{2})([\d]{3})([\d]{3})|^[\d]{2}.[\d]{3}-[\d]{3}/);
        str = $('#cep').val();    
        var res = patt.test(str);    
    
        if (!res)    
        {
            alert(res);   
            return false;
        }else{
    
    
            return true;    
            }
    }
    
    $("#botao").click(function(event) {
    
    var ok = validarCep();
    
        if (ok == true)
        {
            alert("CEP VALIDO. ESCREVA SEU CODIGO AQUI............");
        }
    
    });
    
        
    13.11.2015 / 00:46