Click here to Skip to main content
15,868,056 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
The problem I think is the var regex = new RegExp("^[0-9]+$"); I think this the problem that I still can insert + character in the middle or the end. So I want it to be like the +6016123456789 like this.

What I have tried:

This the is the code that I;ve have tried but it still the same the + character can be
put everywhere.

JavaScript
$('#hpno').keypress(function (e) {
        var regex = new RegExp("^[0-9]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else
        {
        e.preventDefault();
        alert('Please Enter Valid Phone Number');
        return false;
        }
    });
Posted
Updated 22-Aug-18 19:19pm
v3

1 solution

If you want a single "+" prefix, then try:
^\+?\d+$
But... I'd probably use
^\+?\d{7,15}$
to restrict it to the max length of a number: Telephone numbering plan - Wikipedia[^]

If you are going to play with regular expressions, get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 
Comments
jsc42 16-Aug-18 7:39am    
@OriginalGriff's solution checks the whole field in one go, so change the #().keypress to #().change (I'm not a jQuery expert) and test the field value rather than the event keystroke.
Member 13951173 16-Aug-18 21:31pm    
Its still have problem, when I tried the one u recommend it straight will allow alphabet
OriginalGriff 17-Aug-18 3:24am    
No, it won't - that regex only allows a single (optional) leading "+", followed by between 7 and 15 digits. No alpha characters or punctuation is allowed.

I'd suggest you use the debugger to look at exactly what is going on - I suspect the problem is elsewhere in your code...
Member 13951173 17-Aug-18 4:03am    
new RegExp("^[0-9]+$") Means this change to like this?

new RegExp("^\+?\d{7,15}$") <-- like this?
OriginalGriff 17-Aug-18 4:20am    
So what you are saying is "I didn't try it but it didn't work"?
Is there any point in anyone trying to help you if you ignore what they say?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900