Validate Mobile number using regular expression

后端 未结 7 1450
故里飘歌
故里飘歌 2020-12-30 12:37

I need to validate mobile number. My need:

  1. The number may start with +8801 or 8801 or 01
  2. The next number can be 1 or 5 or 6 or 7 or
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 13:11

    I know, that question was asked long time ago, but i assume that @G. M. Nazmul Hossain want to validate mobile number againt chosen country. I show you, how to do it with free library libphonenumber from Google. It's available for Java, C++ and Javascript, but there're also fork for PHP and, i believe, other languages.

    +880 tells me that it's country code for Bangladesh. Let's try to validate example numbers with following code in Javascript:

    String bdNumberStr = "8801711419556"
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    try {
        //BD is default country code for Bangladesh (used for number without 880 at the begginning)
        PhoneNumber bdNumberProto = phoneUtil.parse(bdNumberStr, "BD");
    } catch (NumberParseException e) {
        System.err.println("NumberParseException was thrown: " + e.toString());
    }
    boolean isValid = phoneUtil.isValidNumber(bdNumberProto); // returns true
    

    That code will handle also numbers with spaces in it (for example "880 17 11 41 95 56"), or even with 00880 at the beggininng (+ is sometimes replaced with 00).

    Try it out yourself on demo page. Validates all of provided examples and even more.

提交回复
热议问题