Regex for phone numbers.

Andrew122
Mega Expert

I'm not too good with Regex.  Does anyone know how I could format it so that a phone number field will accept only numbers, parentheses, and minus signs?  Currently it's set up as /^\d+$/ and the field only accepts numbers.

1 ACCEPTED SOLUTION

Dinesh Nikam
Mega Guru

Hello ,

For validation you have to create on change client script on mobile number field

Attaching screen shot for the same

find_real_file.png 

******************code snippet********************

function onChange(control, oldValue, newValue, isLoading) {
if(isLoading || newValue == ''){
return;
}
// Allows formats of (999) 999-9999, 999-999-9999, and 9999999999
var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;
if(!pattern.test(newValue)){
alert('Phone enter a valid phone number');
g_form.setValue('u_mobile_number', '');
}
}

**************************************************

 Thank you,

PLEASE mark my ANSWER as CORRECT if it served your purpose.

View solution in original post

5 REPLIES 5

Dubz
Mega Sage
 // Allows formats of (999) 999-9999, 999-999-9999, and 9999999999



   var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;

 

**Lifted from Brad's response here

Hm, that's not working.  My code is

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}
	var phoneNum = g_form.getValue('u_phone');
	var displayNum = '(' + phoneNum.substr(0,3) + ')' + phoneNum.substr(3,3) + '-' + phoneNum.substr(6,4);
	var rx = new RegExp(/^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/);
	if (!rx.test(newValue)) {
		g_form.setValue('u_phone','');
		g_form.showFieldMsg('u_phone', 'The field will only contain digits.', 'error');
	}else{
		g_form.setValue('u_phone', displayNum);
	}
}

What format do the numbers entered in your u_phone field come in? Must be quite consistent if you're able to format them into a string with your displayNum variable? 

If you're just getting a series of numbers in your u_phone field you could do the regex check there and just confirm you're getting the right number of numbers eg /[0-9]{10}/

If you want to format them into your displayNum variable then do the regex you'll need to change the test to check the displayNum variable eg 

if (!rx.test(displayNum)) {

Shrutika Surwad
Kilo Guru

Hey

Try This Code:

var phone = g_form.getValue('mobile_phone');

 

if (!(/^[0-9]{10}$/.test(phone))) {

 

          alert("Enter 10 digit phone number");

 

          g_form.setValue('mobile_phone',' ')

 

      }

 

Thanks,

Shrutika Surwade

find_real_file.png