Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

form validation

Status
Not open for further replies.

irate

Programmer
Jan 29, 2001
92
GB
can anyone show me a quick script that will check a text box to make sure it only contains numbers?

ie.

<form action=&quot;executescript.asp&quot; method=&quot;post&quot;>
<input type=&quot;text&quot; name=&quot;cost&quot;>
</form>

make sure the text box only contains the characters 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
 
Try this:
Code:
function checkNumber(NumberField){
	var pattern =/\D/;
	var text = NumberField.value;
	var result = text.match(pattern);
	if(NumberField.value==&quot;&quot;){
		NumberField.value = 0;
		return true;	
	}
	else{ 
		if((result != null)){
			alert(&quot;You must enter a number in this field.\nPlease do not enter letters or decimal points&quot;);
			NumberField.focus();
			NumberField.select();
			return false;
		}
		else{
			return true;
		}
	}
}
[code]

This works well for integers and could easily be adapted for decimals. I call it like this:
[code]
<INPUT NAME=&quot;Number&quot; VALUE=&quot;&quot; onChange=&quot;
	if(!checkNumber(this))
		return false;
&quot;>
 
These functions do it, not so simple but its ok

function isInteger (s)

{ var i;

if (isEmpty(s))
// Search through string's characters one by one
// until we find a non-numeric character.
// When we do, return false; if we don't, return true.

for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);

if (!isDigit(c)) return false;
}

// All characters are numbers.
return true;

}

function isDigit (c)
{ return ((c >= &quot;0&quot;) && (c <= &quot;9&quot;))
}
 
I found this code on the netscape website

floatValue=parseFloat(toFloat)
if (isNaN(floatValue))
{ notFloat()}
else
{ isFloat()}





did you not know this or is there a reason why you wouldnt use this or it is bad?
 
I came up with that function when I first started working with Javascript and didn't know anything (as if I know anything now). It's worked for me so I never bothered to look for anything else.

The one you found looks like it would work fine.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top