Validate that text field is numeric usiung jQuery
I know there isn't any need to add a plugin for this.
But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.
The rest of karim79's answer is super cool.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="jquery.numeric.js"></script>
</head>
<body>
<form>
Numbers only:
<input class="numeric" type="text" />
Integers only:
<input class="integer" type="text" />
No negative values:
<input class="positive" type="text" />
No negative values (integer only):
<input class="positive-integer" type="text" />
<a href="#" id="remove">Remove numeric</a>
</form>
<script type="text/javascript">
$(".numeric").numeric();
$(".integer").numeric(false, function() {
alert("Integers only");
this.value = "";
this.focus();
});
$(".positive").numeric({ negative: false },
function() {
alert("No negative values");
this.value = "";
this.focus();
});
$(".positive-integer").numeric({ decimal: false, negative: false },
function() {
alert("Positive integers only");
this.value = "";
this.focus();
});
$("#remove").click(
function(e)
{
e.preventDefault();
$(".numeric,.integer,.positive").removeNumeric();
}
);
</script>
</body>
</html>
Regex isn't needed, nor is plugins
if (isNaN($('#Field').val() / 1) == false) {
your code here
}
This should work. I would trim the whitespace from the input field first of all:
if($('#Field').val() != "") {
var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
errors += "Field must be numeric.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}
I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/
if($('#Field').val() != "")
{
if($.isNumeric($('#Field').val()) {
errors+= "Field must be numeric.<br/>";
success = false;
}
}