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

Silvin
Tera Expert

Hi Clare,

This depends on where you are using this field. I would suggest using the OOB Phone Number(E164) field type. It will do all the validations automatically.

Please refer https://docs.servicenow.com/bundle/paris-platform-administration/page/administer/field-administratio...

Regards,

Silvin Jude Thomas

Hi Silvin,

Is this field type available in Service Catalog? I saw a previous post about this field type on the community but couldn't see it available in the type list.

Thanks,

Clare

Hi Claire,

Unfortunately no, its not available on Service Catalog. For this you will have to do a regex check via client script.

This would be the regex for the expression : /^[\d][\d ]{10,20}$/

var id='1234 3456 897';

var regexp = /^[\d][\d ]{10,20}$/;
var idi = id.match(regexp);

You can goto  https://regex101.com/ and try some regex expressions if you ever want to upgrade to a more better regex because to be honest the current validations you a using "only allow numbers and spaces (no special characters). Min 10 & max 20 characters" is a very weak validation.

Regards,

Silvin Jude Thomas