Validation of CEP Javascript

Asked

Viewed 2,798 times

0

Good morning. I need to validate the typed ZIP code in an input. If the ZIP code is equal to 35000-000, you must clear the input and send an Unavailable ZIP message. Is there a way to do this using the HTML Pattern attribute? How to do?

void validaCEP(){
    var cep = document.commentForm.cep
    if (cep == '35300-000'){
        alert('CEP Indisponível')
        document.commentForm.cep.focus
        alert(cep);
    }
}

Thank you.

  • Have you tried to do anything? Could you add the real problem to the question? Why is the above mentioned zip code invalid? It has the correct formatting of a zip code.

  • Business rule.

  • Dude, I use https://viacep.com.br/ and it works great, I recommend it. It will save you service

  • I used it, but I never had to do this type of validation, with some ZIP code restriction. I need to block the registration of this ZIP code. Is there any way to restrict this on the frontend?

2 answers

5


First, the function definition is wrong. In Javascript we do not declare the function return type, we always use function whether there will be a return or not. Second, its object cep will be the element in the GIFT, an instance of HTMLElement, then it will never be like a string, that is, the condition cep == '35300-000' will never be satisfied. How is a <input>, it is likely that you want to compare the value entered in the field, so what you need to do is access the attribute cep.value.

function validaCEP(){
    var cep = document.commentForm.cep
    if (cep.value == '35300-000'){
        alert('CEP Indisponível');
    }
}
<form name="commentForm">
  <input id="cep" type="text" onblur="validaCEP()">
</form>

2

One way is also to use the function in the Submit event, that is, when trying to submit the form to function will check if the value of the field has the specified value; if it has, it will send Alert, clear the field and abort the sending of the form:

var form = document.commentForm;

form.onsubmit = function(){
   
   var cep = form.cep;
   if(cep.value == '35300-000'){
      alert('CEP Indisponível');
      cep.value = ''; // limpa o campo
      return false; // cancela o submit
   }
   
}
<form name="commentForm" action="destino.php">
   <input type="text" name="cep" required>
   <br>
   <button>Enviar</button>
</form>

Browser other questions tagged

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