0

I have a field ' sessionid' of type text in an html form. I want the user to enter only numbers ranging 1-12 and no more. if 0 or 13 e.t.c is entered an error is returned.

Here's the html form

Session Id
          </td>
          <td>
            <input type="text" name="session id" />

Thanks.Please Help.

watkib
  • 347
  • 3
  • 11
  • 25
  • 1
    Have you tried something yourself? If yes, could you post what you tried? If not, try. Also, try to [search for it](http://encrypted.google.com/search?q=javascript+limit+number+range). – Albireo Mar 04 '11 at 11:47
  • I love it when know-it-all's tell newbies to go look and search for it, he did, he came here! – gettingThereSlowly Jan 31 '14 at 13:10

3 Answers3

5

Try converting the number to an int:

 <script type="text/javascript">
    function checksession(sess){
      var i = parseInt(sess);
      if(isNaN(c) || c < 1 || c > 12){
        alert("Invalid session id!");
      }
    }
</script>

For modern browsers, I'd recommend to use the HTML5 number input type:

<input type="number" name="sessionid" min="0" max="12" >
chiborg
  • 26,978
  • 14
  • 97
  • 115
1

You can use regular expressions.

http://www.javascriptkit.com/javatutors/re.shtml

http://www.regular-expressions.info/numericranges.html

     <script language="JavaScript1.2">
function checkpostal(){
var regexp=/^([1-9]|10|11|12)$/ //regular expression 
if (document.myform.sessionid.value.search(regexp)==-1) //if match failed
alert("wrong input")
}
</script>

<form name="myform">
<input type="text" name="sessionid">
<input type="button" onClick="checkpostal()" value="check">
Tunca Ersoy
  • 339
  • 1
  • 4
  • 18
1

Easiest way would be use a select field

<select name="number-chooser">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">Three</option>
    <option value="4">4</option>
</select>

This is fine for small number spaces, but if you are going a lot bigger REGEXP is your friend.

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • Thanks.I think for my case 'option value' might be more appropriate because the range is small.Thanks @Tunca for the regxp all the same. – watkib Mar 07 '11 at 05:38