Sert string field to minimum characters and numbers only

Thomas G
Tera Guru

Hi,

I have an onChange Client Script ensuring that minimum eight characters are entered in a string field.

 

It looks like this:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var myFieldValue = g_form.getValue('u_account_number');
if (myFieldValue.toString().length < 8 ) {
g_form.setValue('u_account_number','');
alert('Please enter 8 or more characters.');}
}

 

Now I want to expand that so that only numbers from 0 to 9 should be possible. How can I achieve that?

Best regards
Thomas

1 ACCEPTED SOLUTION

Hi Thomas

 

Did you try the regex option suggested by Jerick, that works.

or you can also do this too which is same as Validation regex but through script.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    var regexp = /^[+]?\d*$/;
    var myFieldValue = g_form.getValue('u_account_number');
    if (regexp.test(newValue)) {
        if (myFieldValue.toString().length < 😎 {
            g_form.setValue('u_account_number', '');
            alert('Please enter 8 or more characters.');
        }
    } else {
        g_form.setValue('u_account_number', '');
        alert('Please enter Numbers');
    }
}

 

 


Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

View solution in original post

16 REPLIES 16

Jerick I
Kilo Sage
Kilo Sage

Hi @Thomas G,

 

If this field is a catalog variable there is an existing regex validation see screenshot below for reference.

 

JerickInovero_0-1669707398646.png

 

Thomas G
Tera Guru

Hi Jerick,

Thanks for your reply. I should have mentioned that it is a string field on the incident table so alas no regex type as an option.


Best regards
Thomas

Voona Rohila
Kilo Patron
Kilo Patron

Hi @Thomas G 

 

You want to valiate the length and numbers? Can you explain in detail of your requirement with few examples.


Mark it helpful if this helps you to understand. Accept solution if this give you the answer you're looking for
Kind Regards,
Rohila V
2022-25 ServiceNow Community MVP

Hi Rohila,

Yes; I want to validate both minimum length and make sure that only numbers are allowed. It should only be possible to enter numbers between 0 and 9 but the number entered should be minimum eight numbers long. Eg.: 20028929

 

Best regards
Thomas