1

I have some input number fields, and i prevented some key inputs such as "e", "+", "-" ... I was wondering if it's possible to add another constraint about maximum length in the same control.

maxlength doesn't work, i've added max and min, but my scope is to prevent user from typing more than 2 digits.

   <input type="number" class="form-control"
          onkeydown="return (event.keyCode !== 69 && event.keyCode !== 109 && event.keyCode !== 107 && event.keyCode !== 187 && event.keyCode !== 189 )"
          id="inputMVD" formControlName="dataEvaluationMonth" maxlength="2" name="Month" min="1" max="12" required>

as i wrote above, I need to prevent the user from typing a specific number of digits ( it could be 2 or 4 or 10)

M. Sgarbossa
  • 105
  • 1
  • 1
  • 11

3 Answers3

2

You can call a regex every time the input changes, to format the input:

const handleKeyDown = e => e.target.value = e.target.value.match(/^([^e+-]{0,2})/)[0]
<input type="text" oninput="handleKeyDown(event)">
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • this has worked fine for me, but i had to convert it into ts – M. Sgarbossa Jul 11 '19 at 06:56
  • @M.Sgarbossa Sounds good, I didn't realise you wanted me to write it in typescript. If you need anymore help, don't be afraid to ask, and if you found the answer has helped you, feel free to mark this answer as the correct answer – Kobe Jul 11 '19 at 07:20
1

Try following HTML attributes in input-

 <input type="text" name="usrname" maxlength="2" pattern="[A-Za-z]{2}">

Provide your required allowed pattern like "[1,2]{2}"
Ismail
  • 1,188
  • 13
  • 31
  • my input is type="number", this makes maxlength unusable – M. Sgarbossa Jul 09 '19 at 10:48
  • @Sgarbossa By design when type="number" then maxLength is ignored. Please check this answer [link](https://stackoverflow.com/questions/18510845/maxlength-ignored-for-input-type-number-in-chrome) – Ismail Jul 11 '19 at 04:14
0

Use onkeydown event wich a custom js function, then after all your controls you can decide to prevent the event or to continue.

function myFunction(event) {
  event.preventDefault();
  event.stopPropagation();
  alert("You pressed a key inside the input field");
}
<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" onkeydown="myFunction(event)">


</body>
</html>