Yann Lauwers
Yann Lauwers

Reputation: 31

How to allow the user to only write numbers between 00 and 24

Here is my problem: I'd like to allow the user to write only numbers between 00 and 24.

Js code :

const putRealTime = () => {
    const hoursRangePattern = /^(2[0-3]|1[0-9]|[0-9])$/;

    document.querySelector(".hour-min-input").addEventListener("keypress", (e) => {
        if (e.which < 48 || e.which > 57) {
            e.preventDefault();
        }
    })

    document.querySelector(".hour-min-input").addEventListener("keypress", (e) => {
        const eKey = parseInt(e.key)
        if (hoursRangePattern.test(eKey)) {
            e.preventDefault()
        }
    })
}

Ruby code :

            <div class="hours-container-1">
              <p class="">Your event will start at :</p>
              <div class="hours-container-2 align-items-end">
                <%= f.input :min_timeh, label: false, placeholder: "hh", input_html: { min: '0', max: '24', step: '1' }, input_html: { class: 'hour-min-input', maxlength: 2 }%>
                <p class="double-point">:</p>
                <%= f.input :min_timem, label: false, placeholder:"mm", input_html: { min: '0', max: '59', step: '1' }, input_html: { class: 'min-min-input', maxlength: 2 }%>
              </div>
            </div>

Thank you very much!

Upvotes: 0

Views: 82

Answers (4)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

Wish my regex-fu skills were better...

const input = document.querySelector(".hour-min-input")

const putRealTime = () => {

    input.addEventListener("keydown", (event) => {
        const key = event.key;
        const value = event.target.value;
        const length = value.length;
        
        if (key === "Backspace") {
          return;
        }

        if((length === 0 && !/^[0-2]$/g.test(key))
        || (length === 1 && Number(value) === 1 && !/^[0-9]$/g.test(key))
        || (length === 1 && Number(value) === 2 && !/^[0-3]$/g.test(key))
        || (length >= 2)
        ) {
          return event.preventDefault()
        }
        
    })
}

putRealTime();
<input type="text" class="hour-min-input">

Upvotes: 0

widjajayd
widjajayd

Reputation: 6253

in js you can some thing like:

var regexp, x;
x = $(this).val();
regexp = /([01][0-9]|[2][0-3]):[0-5][0-9]/;
if (!regexp.test(x)) {
  return $(this).val("00:00");
}

note: for regexp pattern:

  • first part "[01][0-9]" if first digit between 0 or 1 then second digit can be between 0..9
  • or second part "[2][0-3]" if first digit 2 then second digit must between 0..3
  • third part [0-5][0-9] for minute it's only allow between 00 - 59
  • if it's not pass the regexp then we overwrite with 00:00

Upvotes: 1

Yshmarov
Yshmarov

Reputation: 3729

You are using f.input, so I assume you have gem 'simple_form' installed. In simple_form:

= f.input :min_timeh, label: false, placeolder: "hh", collection: 0..23
= f.input :min_timem, label: false, placeolder: "mm", collection: 0..59

You do not need extra javascript for this.

Additionally, you can add the following validation to your Model that contains the 2 columns min_timeh & min_timem:

validates :min_timeh, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 23 }
validates :min_timem, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 59 }

If you do want to make the validation more "fancy", here's a gem https://github.com/DavyJonesLocker/client_side_validations

Upvotes: 2

jmcgrory
jmcgrory

Reputation: 843

On your keypress events you will want to validate the input value, to access the value something like:

document.querySelector(".hour-min-input").addEventListener("keypress", (e) => {
  const value = Math.min(24, Math.max(0, e.target.value));
  e.target.value = value;
  const eKey = parseInt(e.key)
  if (hoursRangePattern.test(eKey)) {
    e.preventDefault()
  }
})

Bundle up those 2 new lines in a function that takes an event/min/max as a set of arguments and apply it to both events returned by the event listener callbacks.

Upvotes: 1

Related Questions