mauzilla
mauzilla

Reputation: 3592

South African Mobile Javascript Regex

I'm writing a simple mobile number validator in Javascript but cannot get the regex working correctly.

South African mobile numbers currently are set to:

So example 0821234567 but people may also enter it as 082 123 4567 (with spaces or another way). I want to use regex to test as appose to just checking for numeric as I found 082123456d would also come back as valid.

Here is my sample function:

<script type="text/javascript">

        function regex(number) {
            var regex = /0[678]\d[0-9]\d[0-9]{7,}\d/g;
            if (regex.test(number) === true) {
                console.log("work");
            } else {
                console.log("no");
            }
        }
    </script>

Upvotes: 2

Views: 2646

Answers (1)

Dimag Kharab
Dimag Kharab

Reputation: 4519

var number = '0821234568'; //082123456d or 082 123 4567

var trimmed = number.replace(/\s/g, '');

var regex = /^0(6|7|8){1}[0-9]{1}[0-9]{7}$/;

if (regex.test(trimmed) === true) {
    console.log("work");
else
    console.log("no");

Upvotes: 3

Related Questions