faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 2 of 3 people (67%) answered Yes

Entry

Is it possible to validate a text field in a form so the entered val can only be multiples of 100?

Jun 25th, 2003 13:07
Jean-Bernard Valentaten, Brad Weir, Rich Apperly,


Try this.  It searches the string for 00 and checks to see if it is the 
last 2 characters in the string.  Still doesn't account for someone 
entering 000, or 0000, etc though.
<html>
<head>
<script language="javascript">
function check00() {
var l=document.myform.reward.value.length; //checks length of the string
var v=document.myform.reward.value; //stores the value of the string
var i=v.lastIndexOf("00");
//checks where the string '00'starts.
//first character in string is at position 0
var I=l-2 //subtracts 2 from the length, where the 00 should start
//now the function that pulls it all together
//checks length-2 is equal to where '00' starts
//also checks to see if field is not valued '-1' or '0'
// tested in IE 6.0
if (I==i && I != -1 && I != 0){
alert('value is a multiple of 100')
}
else {
alert('value is not a multiple of 100')
}
}
</script>
</head>
<body>
<form name="myform">
Please enter my reward <input type="text" name="reward"><br>
<input type="submit" onClick="check00();">
</form>
</body>
</html>
****
Good idea Brad, but I think this can be speed up by using a regular 
Expression that checks whether the first character is a digit unequal 
to '0' and whether the string consists of digits only with the last two 
characters beeing '00' (one could try to enter '1abc00' *g*)
<script language="javascript">
<!--
  function check00()
  {
    var v=document.myform.reward.value; //stores the value of the string
    if (v.match(/^[1-9]\d*00$/))
      alert('value is a multiple of 100');
    else
      alert('value is not a multiple of 100');
  }
//-->
</script>