Ashish Bahl
Ashish Bahl

Reputation: 1493

comma separated phone number validation

In the code below, I have a phone number field and what I want to achieve is make sure each number is 15 digits and also ensure that if multiple phone numbers are entered (comma separated) (see code to understand), they too are 15 digits.

$("#btn").on('click',function(){
var regrExpr = new RegExp("^(?=\S{10,}$)(?=.*\d{15},?).*");
//var regrExpr = new RegExp("\d{15}(?:,\d{15})*");
//var regrExpr = new RegExp("\d{10,15}(?:,\d{10,15})*");
//var regrExpr = new RegExp("^(\d{15}[,]{0,1})+$");
//var regrExpr = new RegExp("^\+\d{10,15}(,\+\d{10,15})*$");
//var regrExpr = new RegExp("^(?=\S{10,}$)(?=.*\d{15},?).*");
				if (!regrExpr.test($("#txt").val())) 
			{
					alert("Please Enter No");
				    return false;
			}
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="tel" id="txt" style="width:300px">
<button id = "btn">Check</button>

Regex'ically, I need something like this :

~^[0-15]{15}(?:,[0-15]{15})*$~

Found this here

But, it doesn't work in my case.

Upvotes: 0

Views: 2131

Answers (4)

JustPBK
JustPBK

Reputation: 35

Finally i got a solution Check this Answer

var pattern = /^(?:\s*\d{15}\s*(?:,|$))+$/;

if(pattern.test($("#txt").val())){
  alert("Correct");
} else {
  alert("Wrong");
}

``

Upvotes: 0

Toto
Toto

Reputation: 91438

Use /.../ notation to define regex:

$("#btn").on('click',function(){
    var regrExpr = /^\d{15}(?:,\d{15})*^/;
    if (!regrExpr.test($("#txt").val())) {
        console.log("Invalid number, retry");
        return false;
    } else {
        console.log("All correct")
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="tel" id="txt" style="width:300px">
<button id = "btn">Check</button>

Upvotes: 0

marvel308
marvel308

Reputation: 10458

I believe the best regex would be

^(?=\S{10,}$)(?=.*\d{15},?).*

check the demo at here

here

(?=\S{10,}$)

ensures that the string is atleast of length 10

(?=.*\d{15},?)

is responsible for matching if number is of 15 length and is comma seperated

Upvotes: 1

Osama
Osama

Reputation: 3040

here is the working regular expression of your case.

^\+\d{10,15}(,\+\d{10,15})*$

Upvotes: 1

Related Questions