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.

2
  • 1
    Have you tried something yourself? If yes, could you post what you tried? If not, try. Also, try to search for it. Commented Mar 4, 2011 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! Commented Jan 31, 2014 at 13:10

3 Answers 3

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" >
Sign up to request clarification or add additional context in comments.

2 Comments

@chilborg how can we test for this feature to see if the browser support it?
Use the Modernizr library or read this tutorial: diveintohtml5.org/detect.html#input-types
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.

1 Comment

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.
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">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.