3
I’m having problems with my script, when the zip code field is already formatted, it clears the field by clicking again on the button. How do I make it not to accuse as invalid format or not clear 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>
I like your example. Very good, my intention would be to use both Regex and compare using "|", but it didn’t even occur to me to use "*". Thanks for the help!
– Kelly Soares