Phone validation regex

后端 未结 16 1537
孤城傲影
孤城傲影 2020-11-27 02:56

I\'m using this pattern to check the validation of a phone number

^[0-9\\-\\+]{9,15}$

It\'s works for 0771234567 and +0

16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 03:47

    Consider:

    ^\+?[0-9]{3}-?[0-9]{6,12}$
    

    This only allows + at the beginning; it requires 3 digits, followed by an optional dash, followed by 6-12 more digits.

    Note that the original regex allows 'phone numbers' such as 70+12---12+92, which is a bit more liberal than you probably had in mind.


    The question was amended to add:

    +077-1-23-45-67 and +077-123-45-6-7

    You now probably need to be using a regex system that supports alternatives:

    ^\+?[0-9]{3}-?([0-9]{7}|[0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}|[0-9]{3}-[0-9]{2}-[0-9]-[0-9])$
    

    The first alternative is seven digits; the second is 1-23-45-67; the third is 123-45-6-7. These all share the optional plus + followed by 3 digits and an optional dash - prefix.

    The comment below mentions another pattern:

    +077-12-34-567

    It is not at all clear what the general pattern should be - maybe one or more digits separated by dashes; digits at front and back?

    ^\+?[0-9]{3}-?[0-9](-[0-9]+)+$
    

    This will allow the '+077-' prefix, followed by any sequence of digits alternating with dashes, with at least one digit between each dash and no dash at the end.

提交回复
热议问题