How do I only allow numbers and a special character in javascript?

2

I have a validation problem on the client-side in case I am trying to validate the CEP field, I need it to only accept the person's 9 zip code numbers and the - who can help thank you right away.

This is part of the code:

if(isNaN(cep) || tc.length<10){
   alert('digite seu cep corretamente');
   document.form.cep.style.background='red';
   return false;
}

This code is conflicting with my need because I put it to accept only numbers with isNaN and I do not know how to accept numbers and only a special character.

    
asked by anonymous 02.11.2016 / 01:06

3 answers

1

An alternative would be to use a mask plugin with jQuery:

$('#txtCep').mask('99999-999');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><scriptsrc="https://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.js"></script>

<form>
  CEP: <input type="text" id="txtCep" />
</form>
    
02.11.2016 / 02:21
2

I suggest you have a function that clears whitespace and then checks the 5 digitos > traço > 3 digitos structure. It could look like this:

function isCEP(str) {
    return !!str.split(' ').join('').match(/^\d{5}\-\d{3}$/);
}

['12345-678', '123 45 - 678 ', '12345678', '1234-5678'].forEach(function(cep) {
    console.log(isCEP(cep));
});

In regex I use% w / o of% that means numeric / digit,% w / o of% that means stroke, and% w / o of% which means that it expects x times the type of character before% w_ of% in regex. >     

02.11.2016 / 08:04
2

Your code would look like this with a check for regex :

if (!/^[0-9]{5}\-[0-9]{3}$/.test(cep)){
   alert('digite seu cep corretamente');
   document.form.cep.style.background='red';
   return false;
}

EDIT 1

Complementing with some explanation following the example of @ Sergio ♦

In% with% above% with% means the beginning of the string, that is, nothing different will be accepted than the following. regex means that digits of ^ to [0-9] are accepted. The 0 tells the number of times that the previous term will appear consecutively. 9 means exactly the {X} character. The \- requires that it be the end of the string, thus preventing anything else after it has been tested. The - sequence can also be changed to $ , and the result would be as follows:

/^\d{5}\-\d{3}$/
    
02.11.2016 / 01:39