SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2010
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Red face How to make allowed values are 1 to 7, n and blank only?

    I am just new with javascript and I only need to allow values when submitted. Allowed values are 1 to 7, n and blank only... How to restrict others? I just started below to allow 1 to 7 but for n and blank, I don't know yet.

    JAVASCRIPT:
    Code:
    function verify(frm) {
    	if (frm.sc_scores.value > 7 || frm.sc_scores.value <= 0) {
    		self.alert(frm.sc_scores.value + " is an invalid value! Allowed values are 1 to 7, n and blank");
    		frm.sc_scores.focus();
    	}
    }

    HTML:
    Code:
    <input type="text" name="sc_scores" id="sc_scores" maxlength="1" size="2" value="<%= number %>" />
    Code:
    <input type="button" onClick="verify(this.form)" value="Edit" />
    Please help... Thanks....

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,051
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hello,

    You can do it with a regular expression which tests for any of the permitted characters. E.g.

    Code:
    /^[1-7n]?$/
    This will match a string of one character in length, consisting of the digits one to seven or an 'n'
    The question mark makes everything optional, which means that if the field is submitted empty, validation will still pass.

    Code:
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <title>Validate score</title>
      </head>
      <body>
        <form id="myForm">
          <p>
            <label for="firstName">Please enter your score:</label>
            <input type="text" id="score" />
          </p>
          
          <input type="submit" value="Submit">
        </form>
      
      <script>
        var f = document.getElementById('myForm');
        f.onsubmit = function(){
          if(!(/^[1-7n]?$/).test(f.score.value)){
            alert(f.score.value + "is an invalid value! Allowed values are 1 to 7, n and blank");
            return false
          }
        }
      </script>
      </body>
    </html>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •