Andy
Andy

Reputation: 169

regex for input number and . allowing commas

I have a form submission where I have the person enter an amount.

I have it working fine to reject $ and anything but numbers but it is allowing commas and i cannot seem to get it to stop doing this.

The code is ColdFusion but it is not a CF issue but a RegEx one.

 <cfinput type="Text" 
  name="sp_price" 
  value="0" 
  message="Add-on Price - Numbers Only" 
  validate="regular_expression" 
  pattern="^[0-9].*$" required="No" size="5">

Accepts 1000 1000.00 and 1,000.00 and 1,000 and the I don't want the commas accepted.

Thanks in advance andy

Upvotes: 3

Views: 1610

Answers (3)

Michael
Michael

Reputation: 104

If you want to exclude characters, the format would be [^,]

Example:

pattern="^([0-9]|[^,$\w])*$"

Edit: excludes dollar and word characters https://regex101.com/r/tK5zU7/1

Upvotes: 0

Mario Tacke
Mario Tacke

Reputation: 5498

You can try this:

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

  • 1000 - matches
  • 1000.00 - matches
  • 1,000.00 - does not match
  • 1,000 - does not match

It matches full numbers of any length and optionally decimals of length two. Try the link below.

https://regex101.com/r/kN8zL0/1

Upvotes: 1

anubhava
anubhava

Reputation: 786359

You can make your regex more restrictive like this:

"^[0-9]+(?:\.[0-9]{1,2})?$"

which will only allow integers or decimal numbers but no comma or $ etc.

Upvotes: 1

Related Questions