Search code examples
javascriptruby-on-railssimple-form

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!


Solution

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