Good day! Faced the problem of restrictions on entering characters in the input field for a phone number. I have a script that allows you to enter only numbers in this field, but is it possible to make valid not only numbers, but symbols:

+, -, (space), ()

Thanks in advance, I attached my code below:

function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; }; 
 Enter you number: <input v-model="phone" type="text" maxlength="22" onkeyup="validate(this)" v-validate="'required|alpha_spaces'" data-vv-as="Telefono" onkeypress="return isNumberKey(event)" :class="{'input': true, 'is-danger': errors.has('phone') }"> 

  • one
    You can correct the if condition and add the necessary character codes there. ascii.cl - Dmitry B.

2 answers 2

Refer to the ASCII table

 function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode != 32 && charCode != 40 && charCode != 41 && charCode != 43 && charCode != 45 && charCode < 48 || charCode > 57) return false; return true; }; 
 Enter you number: <input v-model="phone" type="text" maxlength="22" onkeyup="validate(this)" v-validate="'required|alpha_spaces'" data-vv-as="Telefono" onkeypress="return isNumberKey(event)" :class="{'input': true, 'is-danger': errors.has('phone') }"> 

    Get better already ready for this maskedinput plugin. By default, it allows you to specify masks for entering characters / numbers / characters + numbers, but you can also set your own using $ .mask.definitions [e] = '[0-9a-zA-Z + -]' and here you specify the valid characters . And you’ll use it in the form $ ('. Mask'). Mask ('+ 7 (eee) eee-ee-ee') Although I’m using the mask to enter the phone +7 (999) 999-99-99 where in place is 9ok allows you to specify any numbers

    • one
      I thought about it, but there you can only make the shape of a phone for a specific country, and I would like to have worldwide, that is, in a free form, as a person wishes, be it +1394472852, then + 1-4828-4324 and so on. That is, free input is restricted. characters. - Isabella Monza
    • @Oleg Severnuy, Same, only change the regular - MedvedevDev
    • then it’s easier to google phone input with a country selection - I have been finding a similar script for a long time, but I don’t remember where it’s possible to choose a country, and the mask was immediately adapted to it. Your task is widespread, so it's easier to find a ready-made plugin rather than writing your own. - Vladimir Novopashin
    • @Vladimir Novopashin, you quickly surrendered) Why not add something like \+?[\d\-\(\) ]+ - MedvedevDev