How to apply regex for getting only numeric values?

Supriya P
Tera Contributor

Hi,

I have a requirement, on "Change Request" there is field Effort Estimation "Type : String". In that field only numeric value should be filled eg: 23.55, 345, 56. For that I have written a onChange client script. Values like ASdsf233 and asd.345 are cleared But it is taking value "123Asfdg" ,"456.fgj" How to clear values like 65768Asdgf.

Client script:

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

var regexp = /^[0-9].*$/;


if (!regexp.test(newValue))
{
alert('It should be numeric fractional entry only');


g_form.setValue('u_effort', '');
}
}

1 ACCEPTED SOLUTION

Another option is to trim the spaces and test the trimmed value.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var regexp = /^[0-9]*(.)?[0-9]*$/; // may or may not have fractional. Fractional should also be numeric
	var str = newValue.trim(); // trim leading and ending spaces
    if (!regexp.test(str)) {
		g_form.clearValue('u_effort');
		g_form.showFieldMsg('u_effort', 'It should be numeric fractional entry only', 'error');
    } else if (str != newValue) {  // if there was leading or ending spaces, set the value to trimmed value
		g_form.setValue('u_effort', str);
	}
}

Execution result.

1. Enter "      5678     "

find_real_file.png

2. Press tab key.

find_real_file.png

View solution in original post

13 REPLIES 13

Anil Lande
Kilo Patron

Hi,

Please check below link and use one fitting your requirement.

https://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-...

 

Thanks,
Anil Lande

Hitoshi Ozawa
Giga Sage

Why use regular expression.

if (isNaN(newValue)) {
  alert('It should be numeric fractional entry only');
  g_form.setValue('u_effort', '');
}

Thank You Hitoshi it is working for me now.

Not applicable

Hitoshi,

Using isNan allows the mathematical constant e 

Field will have values like 1e1, 1000e344 etc