|
Q1717 How do I check that text entered in a text form field is an integer?
irt.org | Knowledge Base | JavaScript | Form | Q1717 [ previous next ]
Q1717 How do I check that text entered in a text form field is an integer?
Try the following. Note, that the validation is performed twice, once
using an isInteger() function which uses the pasreInt() method to
parse the supplied string value into an integer value, which
unfortunately does not capture string values such as 1.0, and then
again using a regular expression which only allows digits in the
value, but only if the browser supports the window object's RegExp
object:
<html>
<head>
<script language="JavaScript"><!--
function isInteger(value) {
return (parseInt(value) == value);
}
var integer = /^\d+$/;
function validate(form) {
var valid = true;
var output = '';
if (!isInteger(form.myField.value)) {
valid = false;
output += 'Invalid integer value entered\n';
}
if (window.RegExp && !integer.test(form.myField.value)) {
valid = false;
output += 'Invalid integer value entered (regular expression)\n';
}
if (!valid) alert(output);
return valid;
}
//--></script>
</head>
<body>
<form onsubmit="return validate(this)">
<input type="text" name="myField">
<input type="submit" value="Submit">
</form>
</body>
</html>
|
|
|
Copyright © 1996-2008 irt.org, All Rights Reserved.