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

Asked

Viewed 1,154 times

2

I have a validation problem in client-side in case I want to validate the ZIP code field, I need it to only accept the 9 numbers of the ZIP code of the person and the trace - from the CEP, who can help, I would like to thank.

This is a 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 to accept only number with the isNaN and do not know how to accept numbers and only a special character.

3 answers

2

Your code would look like this with a check by 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 by following the @Sergio example

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

/^\d{5}\-\d{3}$/
  • 2

    I think the regex could be improved to /^[0-9]{2}. [0-9]{3}-[0-9]{3}$/ since the one you posted allows Zip Codes so "h12345-678" and so "12345-7890"

  • That’s right, I’ll edit with your suggestion

  • 1

    In regex - is a special character and must be escaped.

  • I’ll improve that too then

2

I suggest you have a function that clears the blanks and then checks the structure 5 digitos > traço > 3 digitos. It could be so:

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 use \d which means number/digit, \- which means dash, and {x} which means it waits x times the character type before the {} in regex.

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>

<script src="https://cloud.github.com/downloads/digitalBush/jquery.maskedinput/jquery.maskedinput-1.3.js"></script>

<form>
  CEP: <input type="text" id="txtCep" />
</form>

Browser other questions tagged

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