How to allow number range in regex

harshadakashid
Tera Contributor

There is a field call Destination port which is a single line text field and a OnChange client script is written to allow number or number range (i.e 1119 or 1100-2000)

How to write regex for this??

var regEx = /^\d+$/;
        if (!regEx.test(destination_port)) {

            g_form.showFieldMsg("destination_port", "Please enter valid Destination Port number.", "error");
         
This is only allowing number i.e 110 but it should allow number range i.e 2000-3000.
5 REPLIES 5

Aniket Chavan
Tera Sage
Tera Sage

Hello @harshadakashid ,

Please give a try to the code below and let me know how it works for you.

var regEx = /^\d+(-\d+)?$/;

if (!regEx.test(destination_port)) {
    g_form.showFieldMsg("destination_port", "Please enter a valid Destination Port number or range.", "error");
}

 

Let me know your views on this and Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Aniket

Hello @harshadakashid ,

 

As per your earlier response I have made some minor changes, so please refer the modified code once and let me know your views on this.

var regEx = /^(\d+|\d+-\d+)$/;

if (!regEx.test(destination_port)) {
    g_form.showFieldMsg("destination_port", "Please enter a valid Destination Port number or range.", "error");
}

Tai Vu
Kilo Patron
Kilo Patron

Hi @harshadakashid 

You can try the below regex for your client script.

var regex = /\b(2\d{3}|3000)\b$/;
if (!regex.test(newValue)) {
	g_form.showFieldMsg("destination_port", "Please enter valid Destination Port number.", "error");
}

 

If you're working with Catalog Variable, you can define a new regex validation in the Question Regular Expression [question_regex] table.

Sample.

Screenshot 2024-01-02 at 13.34.22.png

Timi_0-1704177289211.png

Screenshot 2024-01-02 at 13.35.15.png

 

Cheers,

Tai Vu

It should ideally allow any range values, i.e. 1-2 or 100-200 or 101023-202222. Basically it allows - between 2 numbers OR only numbers i.e. 1002 or 100304