puks1978
puks1978

Reputation: 3697

Only allow a single dot point in input field

I have an input field which has:

$(".double").alphanumeric({allow:" ",ichars:"`~!@#$%^&*=_+[]\\{}|;\":,/<>?'-()\/abcdefghijklmnopqrstuvwxyzABCDFEGHIJKLMNOPQRSTUVWXYZ"});

validation applied to it.

I need to further restrict entry so that only a single decimal place can be added e.g. 100.00 or 255.95

The input is used for currency so I need to only allow 1 decimal point. At the moment its allow 100.00.00 which messes up the system!

Thanks

Upvotes: 1

Views: 3289

Answers (2)

RobG
RobG

Reputation: 147413

A simple function to allow an optional leading + or - and only digits with an optional decimal place is:

function validate(value) {
  var re = /^[-+]?\d+(\.\d+)?$/;
  return re.test(value);
}

However since you want money, you might want:

  var re = /^[-+]?\d+(\.\d\d)?$/;

which will require two digits after the decimal place, if there is one.

Upvotes: 1

jwatts1980
jwatts1980

Reputation: 7356

Here is a regex that will only allow positive/negative decimal numbers

^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$

With jquery you can test the value

if (/^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$/.test($(".double").val())) { .... }

Upvotes: 1

Related Questions