Script to validate telephone number to allow only numbers and spaces

ClareM
Tera Expert

I need a script to validate a telephone number field that will only allow numbers and spaces (no special characters). Min 10 & max 20 characters and to show field msg and clear value if invalid value entered.

Can anyone point me in the right direction? Thanks in advance

1 ACCEPTED SOLUTION

Hi,

something like this

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}

	g_form.hideFieldMsg('fieldName');

	var regex = /^[\d\s]{10,20}$/;

	if (newValue != '' && !regex.test(newValue)) {
		g_form.clearValue('fieldName');
		g_form.showFieldMsg("fieldName", "Invalid phone", "error");
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

7 REPLIES 7

manish64
Giga Guru

you can make use of regular expression 

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

What format is the phone number?

Is it US format?

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

It could be any country format so just want to restrict the number of characters to between 10 & 20 and prevent special characters being entered i.e. + and ().

This would then match the validation in our ERP.

Hi,

something like this

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}

	g_form.hideFieldMsg('fieldName');

	var regex = /^[\d\s]{10,20}$/;

	if (newValue != '' && !regex.test(newValue)) {
		g_form.clearValue('fieldName');
		g_form.showFieldMsg("fieldName", "Invalid phone", "error");
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader