RegExp for validating PRICE [closed]

I am trying to validate a Price field:

Should not allow:

  • white spaces
  • alphabets
  • negative values

Should allow:

  • numbers
  • commas
  • decimals

Answers:

Answer

RegExp for validating Price Fields:

/^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/

Explained demo: http://regex101.com/r/uG5lI0/1

Javascript code to validate:

/^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(input)

Will validate only if in correct format, with dots or commas in their respective places.

International format for the en_US locale & US national format:

  • 134.56
  • 1,234.56
  • 2,991,234.00

Italian national format with 2 decimals:

  • 134,56
  • 21.234,56
  • 1.234,56
  • 9.321.234,56

International format for the de_DE locale:

  • 134,56
  • 1234,56
  • 98281234,56

Decimals are optional, validation for whole amounts:

  • 1234
  • 1,234
  • 2,991,234
  • 1.234
  • 9.321.234

function validatePrice(input) {
  return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.test(input);
}

['WRONG',
  '1,234,56',
  '1.234.56',
  '-1993',
  '918,27.63',
  '122.42.24',
  '1,89,2',
  '',
  'Intl. format & US national format',
  '2.56',
  '14.56',
  '134.56',
  '1,234.56',
  '2,991,234.00',
  '',
  'Italian national format with 2 decimals',
  '9,56',
  '24,56',
  '134,56',
  '721.234,56',
  '21.234,56',
  '1.234,56',
  '9.321.234,56',
  '69.321.234,56',
  '269.321.234,56',
  '1.269.321.234,56',
  'International format for the de_DE locale',
  '1,56',
  '14,56',
  '134,56',
  '1234,56',
  '98281234,56',
  'No cents',
  '1',
  '14',
  '134',
  '1,234',
  '2,991,234',
  '9',
  '24',
  '134',
  '1.234',
  '9.321.234',
  '1',
  '14',
  '134',
  '1234',
  '98281234'
].forEach(function(n) {
  document.getElementById('results').innerHTML += "'" + n + "' => " + validatePrice(n) + "<br>";
})
<div id="results"></div>

Answer

This regex ought to do it:

^[\d\.,]+$

Edit:

Here's a better regex, to allow more sane number formats (for US dollars). Still not perfect - would need to know exactly what validation you are expecting, if this isn't quite it.

^(\d{1,3})?(,?\d{3})*(\.\d{2})?$

Answer

It's easiest to just include the things you want and exclude everything else. It looks like you want digits, commas, and periods. A regex for this would look like /^[\d.,]+$/. This doesn't specify any order for the formatting. If you wanted commas to only appear in groups of 3 digits (not great of internationalization, but functional for US) for instance, you would need something more like /^\d{,3}(,\d{3})*(\.\d+)?$/ - 0-3 digits followed by 0 or more groups of ',NNN' with an optional '.N').

If you wanted to separately detect the things you wanted to avoid, you could use something like /[-A-z \t]/ - dash, letters (upper and lower), spaces or tabs.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.