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>