Regex for Numbers which automatically add comma and decimal
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 01:33 AM
Hello,
I have a custom string field on record producer, which should allow only integers with decimals and add commas I have have added below script in catalog script but it's not allowing decimals and user is not allowed to enter only 0 value.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 02:40 AM
@Community Alums
what value you are entering and for which one it's working fine and for which one it's not?
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 02:45 AM
It's working when I number 091212/123.67/6876786/ any of these numbers are working as expected adding commas, when I enter alphabets it's giving error.
But when I enter only 0 to the field it's still giving error which should not be the case
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 02:52 AM
@Community Alums
try this
function onChange(control, oldValue, newValue, isLoading) {
// Don't run on form load or if the value is truly empty
if (isLoading || newValue === '') {
return;
}
var formatted = formatNumber(newValue);
if (formatted === false) {
alert('Only numeric values allowed (integers or decimals).');
g_form.setValue('u_opex_cost_yearly_in_usd', '');
return;
}
// Set formatted value with commas if needed
if (formatted !== newValue) {
g_form.setValue('u_opex_cost_yearly_in_usd', formatted);
}
}
function formatNumber(number) {
// Remove existing commas
number = number.replace(/,/g, '');
// Regex: allows "0", non-zero integers, and decimals
var reg = /^(0|[1-9]\d*)(\.\d+)?$/;
if (!reg.test(number)) {
return false;
}
// Split integer and decimal parts
var parts = number.split('.');
// Add commas to integer part
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// Recombine and return
return parts.length > 1 ? parts[0] + '.' + parts[1] : parts[0];
}
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 03:15 AM
unfortunately same result
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2025 09:40 PM
Field is not allowing to enter single "0" or "00" or "000" but when I enter 4 zeros it allows me and adds comma "0,000".