Javascript Validation Javascript

1

Good morning. I need to validate the CEP typed in an input. If the CEP is equal to 35000-000, you must clear the input and send CEP message Not Available. Is there any 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.

    
asked by anonymous 26.12.2018 / 11:48

2 answers

4

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

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>
    
26.12.2018 / 12:07
2

One way is also to use the function in the submit event, ie when trying to submit the form the function will check if the value of the field has the specified value; if it has, it will issue the alert, clear the field and abort sending 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>
    
26.12.2018 / 12:56