Reputation: 287
Validating a text field value which may be positive whole number or number with one decimal point and one decimal after the point in javascript:
123
1
12345
233.2
1212.2
1.1
are valid numbers and
1.222
1.33
-89789
-3
are invalid numbers.
Ihave applied this but not get desired result
function CheckOneDecimal(txtbox) {
if (txtbox.value.length > 0)
{
if (isNaN(txtbox.value)) {
txtbox.value = "";
alert("Please enter number with one decimal places");
txtbox.focus();
return;
}
else if (parseFloat(txtbox.value) > 0)
{
txtbox.value = "";
alert("Please enter number with one decimal places. eg. 8.1");
txtbox.focus();
return;
}
var oRegExp = /^\s*\d+\.\d{1}\s*$/;
if (oRegExp.test(txtbox.value))
{ }
else {
txtbox.value = "";
alert("Please enter number with one decimal places");
txtbox.focus();
}
}
}
Upvotes: 1
Views: 431
Reputation: 91518
I'd do:
/^\d+(?:\.\d)?$/
explanation:
The regular expression:
(?-imsx:^\d+(?:\.\d)?$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\. '.'
----------------------------------------------------------------------
\d digits (0-9)
----------------------------------------------------------------------
)? end of grouping
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Upvotes: 0
Reputation: 94131
This regex should do:
/^\d*\.?\d$/
Demo: http://jsbin.com/ovaVAfU/1/edit
Upvotes: 2