Garima Jain
Garima Jain

Reputation: 17

Regex for pattern integer,integer or float

I want to validate entry in textbox using regex. The pattern should be

integer, integer or float

so valid entries can be

1234, 1234
123, 123.45

and invalid entries will be

abd, 123
123, abc
abc, abc

so far I have tried

var entry = "123,123.4" 
var patt = new RegExp("^[0-9]+,(?:[\d+(\.\d+]+,?){0,1}$");
res = patt.test(entry);  

but it returns false, though it should return true

Upvotes: 1

Views: 5286

Answers (5)

Abhishek Gautam
Abhishek Gautam

Reputation: 1767

Try this one:

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

652.16 valid

.12 invalid

511.22 valid

1.23 valid

12.3 valid

12.34 valid

Upvotes: 0

Dhaval
Dhaval

Reputation: 389

First split string by ","

var entry = "123,123.4";
var entryArray = entry.split(',');

then just check entryArray items using following function I got from link

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}

And here is full recipe

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}

function isValidInput(input){
    if (!input) {return false};
    var inputArray = input.split(',');
    inputArray = inputArray.map(function(item){
        return item.trim();
    })
    inputArray = inputArray.filter(function(n){
        var number = parseFloat(n);
        return number && (isInteger(parseFloat(n)) || isFloat(parseFloat(n)) )
    })
    return (inputArray.length === 2)
}
isValidInput("55,55.44");

Upvotes: 2

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Replace you regExp by this one:

var reg = new RegExp("^[0-9]+,[0-9]+.?[0-9]*");

I think this is what you want.

To accept space after comma:

var reg = new RegExp("^[0-9]+, [0-9]+.?[0-9]*");

For case of 1a it's needed to ad $ in the end

Upvotes: 0

Sebastian Proske
Sebastian Proske

Reputation: 8413

Seems like you mixed up the second part of your regex a bit. ^\d+,\s*\d+(?:\.\d+)?$ should be what you need.

Here is a Regex101 sample.

  • \d+ matches one or more digits (an integer)
  • ,\s* matches comma, optionally followed by spaces
  • \d+(?:\.\d+)? matches one or more digits, optionally followed by a dot and one or more digits (an integer or float)

Note1: This will not match negative numbers. You could adjust your regex to ^-?\d+,\s*-?\d+(?:\.\d+)?$ if this is required

Note2: This will not match .1 as a float, which might be a valid float. You could adjust your regex to ^\d+,\s*(?:\d+|\d*\.\d+)$ if this is required.

Upvotes: 4

scel.pi
scel.pi

Reputation: 703

^\d+,\s?\d+\.?\d*$

Will be valid to

1234, 1234
123, 123.45

And Invalid To

abd, 123
123, abc
abc, abc

Upvotes: 0

Related Questions