skip to Main Content

I’m using cleave.js on a web page. My goal is to create a mask that will allow only a 3-digit number to be entered from the input tag. For this I use cleave.js as follows

    <script>
        let number = new Cleave("#numberId", {
                numeral: true,
                delimiter: '',
                blocks: [3],
                numeralThousandsGroupStyle: 'none',
                rawValueTrimPrefix: true,
            });
    </script>

The Html is as follows.

 <input type="text" class="form-control" id="numberId" placeholder="Enter a 3-digit number">

Then, I get the values of the input whose id value is numberId as follows.

    <script>
         let value = $("#numberId").val();
    </script>

The problem I encounter is this: For example; When I write 1234, 123 appears on the screen, but when I take the input value, it appears as 1234. When I enter 12345, 123 appears on the screen, but when I take the input value, it appears as 1234.
What I want is this: Even if 1234 or 12345 is entered, 123 should appear on the screen and the value coming from the input should be 123.
How can I solve this problem?

2

Answers


  1. You could have an event listener that listens for input and then cut off the digits if there are too many.

    Alternative, the attribute max will validate that the number is not higher than 999, but that only has an effect if you leave out the input event listener. So, you would be allowed to write more digits, but the form will only submit if the number is 999 or less.

    document.forms.form01.num.addEventListener('input', e => {
      e.target.value = e.target.value.substring(0, 3);
    });
    
    document.forms.form01.addEventListener('submit', e => {
      e.preventDefault();
      console.log(e.target.num.value);
    });
    <form name="form01">
      <input type="number" name="num" max="999" />
      <button>Submit</button>
    </form>
    Login or Signup to reply.
  2. The answer of @chrwahl is good! Here is another way it could work, without using Cleave.js library.

    You could use the pattern attribute on your input. "The pattern attribute specifies a regular expression the form control’s value should match…" – https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

    In this case, the regEx you would need is d{1,4}

    d is a shorthand character class that matches any digit (equivalent to [0-9]).

    {1,4} is a quantifier that means "match between 1 and 4 times".

    So, d{1,3} will match any sequence of one to three digits. For example, it matches "1", "12", "123", "123", but not "" (empty string) or "1234" (because it has more than three digits).

      <form name="form">
       <input type="number" name="num" pattern="d{1,3}" />
       <button>Submit</button>
      </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search