0
let phoneNumber = $('#order-phone').val()

if (phoneNumber.length == 13) {
    parts = phoneNumber.split('-');
    if ((parts[0] == '010') && ((parts[1] >= '0000') && (parts[1] <= '9999')) && ((parts[2] >= '0000') && (parts[2] <= '9999'))) {
        alert('Finished');
    } else {
        alert('Put your number like "010-OOOO-OOOO"');
    }
} else {
    alert('Put your number like "010-OOOO-OOOO"')
}

The situation is like.. The user inputs his phone number as string and then I check the validation for the phone number the user gave to me. 'PhoneNumber' above is string type and I don't know how can I do perfect validate check for the strings that is phone number with 13 characters including numeric characters and hyphen.

Phix
  • 9,364
  • 4
  • 35
  • 62
1105man
  • 1
  • 1
  • 3
    https://github.com/google/libphonenumber/blob/master/FALSEHOODS.md – Stephen P Oct 22 '20 at 17:04
  • you can use regex – Nonik Oct 22 '20 at 17:05
  • 1
    This is what you're looking for,
    https://stackoverflow.com/questions/18375929/validate-phone-number-using-javascript
    – berkobienb Oct 22 '20 at 17:13
  • What's wrong with what you have? It seems to work fine. You _could_ combine the length and parts tests so you don't have to repeat the alert... `if (phoneNumber.length == 13 && ((parts[0] == '010') && ((parts[1] >= '0000') && (parts[1] <= '9999')) && ((parts[2] >= '0000') && (parts[2] <= '9999')))) {` – Stephen P Oct 22 '20 at 17:20

1 Answers1

0

Use javascript regex for validation. The length check is not necessary, the regex will take care of that. The regex below is the global regex for phone number validation. For your check the regex should be option-4 from other regex. This is the code:

let phoneNumber = $('#order-phone').val();
let patt = new RegExp(/^[+]*[0-9]{1,4}-[0-9]{10}$/g); //This is the regex for validation phone number
let res = patt.test(phoneNumber );
console.log(res); //this will return true or false

//alert(res);

Other regex:

  1. /^[+]*[0-9]{1,4}-[0-9]{10}$/g : +XXX-XXXXXXXXXX ('+' is optional)
  2. /^[+]*010-[0-9]{10}$/g : +010-XXXXXXXXXX ('+' is optional)
  3. /^[0-9]{3}[-]{0,1}[0-9]{4}[-]{0,1}[0-9]{4}$/g : XXX-XXXX-XXXX ('-' is optional)
  4. /^[0-9]{3}[-]{1}[0-9]{4}[-]{1}[0-9]{4}$/g : XXX-XXXX-XXXX.
SUMIT PATRO
  • 166
  • 5