简体   繁体   中英

Regex for Kenyan Phone Number format

About a week ago, I came to Stack Overflow to look for a way to validate a Kenyan phone number in JavaScript. I sadly browsed through questions that were about other countries` numbers. So yesterday I succeeded in creating it. I thought its a good idea to share it with you. Especially for Hybrid App (Cordova) and Web developers.

To match 07xx xxx xxx number

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

To match +254 7xx xxx xxx

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

To match 254 7xx xxx xxx

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

To match all the different number formats

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

Head over to Rubular to test.

To check for all number formats as @Denn has illustrated on my angular 7 App i used

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

Then on my app

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

I have used jQuery and HTML. It's good to note that Kenyan phone numbers have a 07## ### ### format. It is meant for developers working with JavaScript in delivering custom services to Kenyan users.

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM