1

Probably done with JavaScript.

See this Example from W3Schools

<input type="number"  size="2" min="1" max="2">

Even with the Min and Max values set, you can still type in whatever number you want and it will accept that value. How do I restrict the user in this case so they can only enter 1 or 2, if they enter something different then it sends an alert and clears the field so the user can try again.

7
  • When do increase or decrease value by click on arrow(right side) then the action will perform according to you. If you put the number mannualy(by typing) then it does not work. Mar 28, 2014 at 17:29
  • What does your current javascript code look like, and what specific problems do you have with it?
    – admdrew
    Mar 28, 2014 at 17:30
  • You'll probably want to add a keypress event to the input and detect the keycode or value - then take action accordingly.
    – Goose
    Mar 28, 2014 at 17:30
  • On each keypress in the input field you can check if you can validate the input text and do necessary
    – rozar
    Mar 28, 2014 at 17:32
  • @user3362232 but you did not say about restriction on cliking right side arrow. Mar 28, 2014 at 17:35

6 Answers 6

4

Without using JS, you can set the pattern attribute of the input field so the user knows at least that what he/she put in is invalid. This will not clear the field however.

DEMO

HTML

<input type="number" size="2" min="1" max="2" pattern="[12]">

CSS

input:invalid { color:red; border:2px solid red; }
2
  • 2
    True, but you'll have trouble carrying this method forward if you want to include numbers with more than a single digit in your range.
    – Paul
    Mar 28, 2014 at 17:45
  • I like this option as well I'm using it with the alert. Thanks.
    – DivineChef
    Mar 28, 2014 at 18:17
2

For simplicity's sake, I'm adding an id to your input:

<input type="number" id="myInput" size="2" min="1" max="2">

Then we can simply add an event listener:

document.querySelector('#myInput').addEventListener('input', function(e) {
  if (e.target.value !== '1' && e.target.value !== '2') {
    alert('Invalid number!');
    e.target.value = '';
    e.preventDefault();
  }
});

JSFiddle example

Keep in mind, it's rather jarring UX to use alert, I'm only using it here for an example. Instead, you may want to add an error class to the element or pop up a modal.

3
  • @Teemu Well, I feel like a dope. Thanks for the catch, it's fixed now. Mar 28, 2014 at 17:36
  • Thanks this is the best solution. I had to put this script at the bottom of the page below the HTML since it uses an event listener. Putting the script at the top didn't work because it didn't load the ID.
    – DivineChef
    Mar 28, 2014 at 18:16
  • @user3362232 That's correct and best practice. Glad I could help, and thanks for the accept/upvote! Mar 28, 2014 at 18:17
1

If you don't mind having a standard error message on invalid input, you can also use:

<input type="text" pattern="[1-2]">

Edit: If you add a "title" attribute to the input, you can set the error message you want.

1

You can use jQuery and checkValidity() method of the input:

$('[name=points]').bind('keyup',function(){
  if (!$(this).get(0).checkValidity()) {
    $(this).val('');
  }
});

checkValidity() will only work in modern browsers.

Demo: http://www.bootply.com/125666

1

The example is using the HTML 5 input type number, which not all browsers support consistently.

You could limit this range using JavaScript, perhaps using jQuery. This is definitely an improvement over the code above, but in truth in a real-world application you accomplish this by using a framework component like AngularJS, Knockout, or jQuery Validator. Using a framework like this will allow you to manage all of your validation in a central location and implement more complex logic involving multiple properties, such as "Value two must be greater than value one".

3
  • Attribute events makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window object, polluting the global namespace. Mar 28, 2014 at 17:59
  • sorry about that Paul .. as soon as I saw the onchange attribute I automatically pasted the comment... if you edit your post I can remove the downvote... Mar 28, 2014 at 18:38
  • 1
    Killed it least a tl;dr programmer adopt it.
    – Paul
    Mar 29, 2014 at 0:32
0

This is how <input type=number> is expected to work: it does not physically prevent the user from entering arbitrary data (well, it might, but it need not), but the control does not satisfy constraints upon form submission, if it does not match the requirements.

If you want to let the user select between two alternatives only, use a checkbox, or two radio buttons, or a select element with two options. The details depend on whether this should be an obligatory choice or optional and whether there is a default value.

P.S. W3schools.com is bogus, in this issue, too. The example you link to (which is different from your code) is not strictly incorrect, just illogical and misleading.

4
  • it does not physically prevent the user from entering arbitrary data To be fair, that's precisely what pattern is for in HTML5.
    – admdrew
    Mar 28, 2014 at 18:13
  • 1
    @admdrew, the question was not about pattern. OTOH, for both pattern and type=number, the whole Constraint validation API would be pointless if browsers were expected to enforce the constraints at the level of individual constraints. Mar 28, 2014 at 18:23
  • @JukkaK.Korpela the question was not about pattern It sure can be! How do I restrict the user...?
    – admdrew
    Mar 28, 2014 at 18:37
  • Pattern is not the correct solution for restricting the user to a range of numbers.
    – Paul
    Mar 29, 2014 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.