简体   繁体   中英

How to validate an interval entered to a text input field

Is there a way to define a number interval (let's say between 1900 and 2016) in jQuery that can only be entered to a text input field?

As far as I understand, I have to use input type="text" because the number field can't be used for a jQuery keyboard. In addition, it is required that values be entered both by a virtual and real keyboard (see http://generace.forbes.cz/ ) and that the number interval be checked each time user tries to submit the form.

This is the far most I can get to without doing any dirty work.

https://jsfiddle.net/mankinchi/uupytLh2/

pattern="\d{4}"

if ((number < 1900) || (number > 2016))

This use the combination of having a pattern to check (4 digits only when submitting) and javascript (I used jQUery) to check for number range. The combination will allow you not messing around with a pattern in low level (limit the exact digit to be inputted).

However, if you still want to limit the user input, not checking afterward, you still can with oninput and manually limit out the next possible options.

There is a jQuery Validation plugin https://jqueryvalidation.org/ that is great for this.

Just embed it and use:

$("#year_form").validate({
  lang: 'cs',
  rules: {
      year: {
      required: true,
      min: 1910,
      max: 2016
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM