肯尼亚电话号码格式的正则表达式

时间:2017-05-24 17:09:34

标签: javascript jquery regex cordova

大约一周前,我来到Stack Overflow寻找一种方法来验证JavaScript中的肯尼亚电话号码。我遗憾地浏览了有关其他国家号码的问题。所以昨天我成功地创造了它。我认为与你分享是一个好主意。特别适用于Hybrid App(Cordova)和Web开发人员。

4 个答案:

答案 0 :(得分:2)

匹配07xx xxx xxx

^0(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$

匹配+254 7xx xxx xxx

^(?:+254)?(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$

匹配254 7xx xxx xxx

^(?:254)?(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$

匹配所有不同的数字格式

^(?:254|\+254|0)?(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$

前往Rubular进行测试。

答案 1 :(得分:1)

要检查所有数字格式,如@Denn在我使用的我的angular 7 App中说明的那样

  keRegexPattern = /^(?:254|\+254|0)?(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$/;

然后在我的应用上

this.registerForm = this.formBuilder.group({
  phone: ['', [Validators.required, Validators.pattern(this.keRegexPattern)]],
});

答案 2 :(得分:1)

要匹配2547XXXXXXXX,请使用以下简单的正则表达式

^254\d{9}$

要匹配07XXXXXXXX,请使用以下简单的正则表达式

^07\d{8}$

答案 3 :(得分:0)

我使用过jQuery和HTML。值得注意的是,肯尼亚的电话号码有07 ## ### ###格式。它适用于使用JavaScript为肯尼亚用户提供定制服务的开发人员。

<script type="text/javascript">
$(document).ready(function(){
    $("#verify").click(function(){

        var phoneNumber = $("#phoneNumber").val();
        var toMatch = /^07\d{8}$/;
        /*
        *Assumming that you have added a script tag to refer to the jQuery library in your HTML head tags
        -for example <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></closing script tag>
        *Assuming you have an HTML input with an id="phoneNumber"
        *Assuming you have a HTML button with an id="verify"
        *Assuming you have a HTML paragraph with an id="result"
        * ^ means matches at the beginning of the line
        * $ means matches at the end of the line
        * \ means backslash escape to make a normal character special
        * /d means a single digit character
        * {n} mean the n occurence of the preceding match
        *the two forward slashes that start and end are basically what enclose our REGEXP 
        *var toMatch = \our pattern\; is the syntax as briefly mentioned in previous comment
         */
        var authenticate = toMatch.test(phoneNumber);
        if (authenticate) {
            $("#phoneNumber").focus();
            $("#result").html("Valid Kenyan Number");

        }else{
            $("#phoneNumber").focus();
            $("#result").html("Invalid Kenyan Number");
        }

    });
});
</script>