Phone number validation on catalog form

raj99918
Tera Contributor

Hi ,

 

Phone number validation on form it should contains only numbers with - and + 

 

How can I achieve this one from regex?

 

Thanks 

10 REPLIES 10

Robbie
Kilo Patron
Kilo Patron

Hi @raj99918,

 

This is ServiceNow's prescribed implementation:

You may however want to play or adjust the regex for your need. Eg:  ^\+[1-9]{1}[0-9]{1,14}$

 

  1. Create a variable of Single Line Text type.
  2. Create the following onChange client script:
    • Type: onChange
    • Variable name: the name of the variable to be use
    • Script:

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

    //Type appropriate comment here, and begin script below
    var pattern = /^[(]?(\d{3})[)]?[-|\s]?(\d{3})[-|\s]?(\d{4})$/;

 

    if (!pattern.test(newValue)) {
        alert('Phone enter a valid phone number');
        g_form.setValue('variable_name', '');
    }
}

*Please note that the above regex / pattern is specific for validating 10 integer digits only. You may modify this regex if there's a need for it to validate any other formats.

 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Helpful.

 

Thanks, Robbie

 

https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0719284

raj99918
Tera Contributor

HI @Robbie  Thanks for the reply, but I want phone number just contains numbers - and + need regex for this case. How can I write for this one?

Thanks

Hi @raj99918,

 

Is there any sort of pattern to the number you wish to apply? 

For a general regex that literally just allows numbers and the '-' and '+' symbols, use the following regex:

/^[0-9+-]*$

 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Helpful.

 

Thanks, Robbie

swathisarang98
Giga Sage
Giga Sage

Hi @raj99918 ,

 

you can use the regex as below in your code,

 

^\+?\d{1,3}-?\d{3}-?\d{3}-?\d{4}$

 

which checks for all below possibilities

+123-456-7890, 123-456-7890, +1-123-456-7890, 1234567890, etc.

 

Please mark this comment as Correct Answer/Helpful if it helped you.

Regards,

Swathi Sarang