Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

User should able to enter number and range should be 0 to 65536

lucky24
Tera Contributor

Hi Team,

We have one port number field and the user should only be able to enter 0 to 65536 and it should also accept (, and Special characters)  

For example :  22-23, 25, 80, 443, 2001-2020

Can someone please let me know how can I achieve this?

 

Thanks

3 REPLIES 3

Rohit99
Mega Sage

Hi @lucky24,

You may try with following onChange Client Script.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '') {
      return;
   }
    var pattern = /^(?:[0-9]|[1-9][0-9]|[1-9][0-9]{2}|[1-9][0-9]{3}|[1-5][0-9]{4}|[6][0-4][0-9]{3}|65[0-4][0-9]|655[0-2][0-9]|6553[0-5][0-9]|65536)$/;
    if (!pattern.test(newValue)) {
        alert("enter correct values");
        g_form.setValue('short_description','');
    }
}  

 

Please mark my response as correct and helpful if it helped solved your question.

 

Thanks,

Rohit Suryawanshi

Jordan Vignoni
Tera Guru

If the field is on a table, you can use an onChange client script that contains a regex.  If the field is on a catalog item, you can create a "Variable Validation Regex" and apply it to the field.

Vrushali  Kolte
Mega Sage

Hello @lucky24 ,

 

To achieve this requirement, you can create on change client script on "port number" field and use regex for validation as below -

 

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

   //Type appropriate comment here, and begin script below

  var portField = g_form.getValue('number_field'); //replace the field name
    
    // Regular expression to validate port numbers and ranges
    var regex = /^\s*(6553[0-6]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[0-9]{1,4})(\s*-\s*(6553[0-6]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[0-9]{1,4}))?(\s*,\s*(6553[0-6]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[0-9]{1,4})(\s*-\s*(6553[0-6]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[0-9]{1,4}))?)*\s*$/;
   

    // Validate the port number field against the regular expression
    if (!regex.test(portField)) {
        alert('Invalid port number format. Please enter values between 0 and 65536, using commas and hyphens as separators.');
    }
   
}

 

VrushaliKolte_0-1723125764589.png

I have tried it in my PDI and it worked for me.

 

If my answer solves your issue, please mark it as Accepted✔️ & Helpful👍!