Regular Expresion

Neha Tiwari5
Tera Contributor

Hi,

 

I need a regular expression for

"Phone number needs to meet following criteria"
"1. Starts with '+'
"2. Followed by digit 1 - 9
"3. Followed by digits 0 - 9 with / without space in between.
4. Should not have any alphabets in it.";

 

via OnChange client script

1 ACCEPTED SOLUTION

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

    var phonePattern = /^\+[1-9][0-9\s]*$/;

    if (!phonePattern.test(newValue)) {
        g_form.showFieldMsg(control.name, 'Phone number must start with + followed by a digit (1-9), and can include digits (0-9) with optional spaces.', 'error');
        g_form.clearValue(control.name);  // Optionally clear the invalid value
    } else {
        g_form.hideFieldMsg(control.name);
    }
}

Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

View solution in original post

3 REPLIES 3

Harshad Wagh
Tera Guru

please try this ^\+[1-9][0-9 ]*$

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

    var phonePattern = /^\+[1-9][0-9\s]*$/;

    if (!phonePattern.test(newValue)) {
        g_form.showFieldMsg(control.name, 'Phone number must start with + followed by a digit (1-9), and can include digits (0-9) with optional spaces.', 'error');
        g_form.clearValue(control.name);  // Optionally clear the invalid value
    } else {
        g_form.hideFieldMsg(control.name);
    }
}

Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark

Community Alums
Not applicable

Hi @Neha Tiwari5 ,

 

Try this code

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

    var pattern = /^\+([1-9])(\d|\s)+$/;
    var result = pattern.test(newValue);

    if (result) {
        g_form.clearErrorMessage('YourVariableName'); 
        g_form.showFieldMsg('YourVariableName', 'Valid phone number', 'info');
    } else {
        g_form.showErrorBox('YourVariableName', 'Invalid phone number. Ensure it starts with +, followed by a digit 1-9, and contains only digits or spaces.');
    }
}

 

If my answer helped you in any way, please mark it as helpful or correct.