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
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
Share Improve this question asked May 20, 2016 at 18:44 Garima JainGarima Jain 171 silver badge5 bronze badges 2- The first one intenger (every) and the second one Integer of Float? – scel.pi Commented May 20, 2016 at 18:53
- regex101./r/fP8qY5/1 – scel.pi Commented May 20, 2016 at 18:59
5 Answers
Reset to default 4Seems 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 ma, 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.
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");
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 ma:
var reg = new RegExp("^[0-9]+, [0-9]+.?[0-9]*");
For case of 1a it's needed to ad $ in the end
^\d+,\s?\d+\.?\d*$
Will be valid to
1234, 1234
123, 123.45
And Invalid To
abd, 123
123, abc
abc, abc
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744388258a4571775.html
评论列表(0条)