开发者

how to Validate a Phone number so that it should not allow all same numerics like 99999999999 or 11111111111 in java

how to Validate a Phone 开发者_如何学Pythonnumber so that it should not allow all same numerics like 99999999999 or 11111111111 in JAVA

thanks Sunny Mate


If feasable, I'd try to discredit that requirement so it will be rejected.

No matter what you put into your plausibility checks, a user trying to avoid mandatory fields by entering junk into them will always succeed. You either end up having "smarter" harder-to-detect junk data items, or having a plausibility check which does not let all real-world data through into the system. Shit in, shit out. Build a shitshield, and your users will create fascies you never imagined.

There is no way to program around that (except for simple things that usually are unintended, erraneously entered typos and so on).


The following regex:

^(\d)(?!\1+$)\d{10}$

matches 11 digit strings that do not have all the same digits.

A demo:

public class Main {
    public static void main(String[] args) throws Exception {
        String[] tests = {
                "11111111111",
                "99999999999",
                "99999999998",
                "12345678900"
        };
        for(String t : tests) {
            System.out.println(t+" :: "+t.matches("(\\d)(?!\\1+$)\\d{10}"));
        }
    }
}

which produces:

11111111111 :: false
99999999999 :: false
99999999998 :: true
12345678900 :: true


This code matches numbers with at least 4 repeated numbers. (You could change the 3 in the regular expression to increase this threshold.)

Pattern sameDigits = Pattern.compile("(\\d)(\\1){3,}");

for (String num : new String[] {
        "11111",  // matches
        "1234",   // does not match
        "8584",   // does not match
        "999",    // does not match (too few repetitions)
        "9999"})  // matches

    if (sameDigits.matcher(num).matches())
        System.out.println("Same digits: " + num);
    else
        System.out.println("Not same digits: " + num);

Prints

Same digits: 11111
Not same digits: 1234
Not same digits: 8584
Not same digits: 999
Same digits: 9999
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜