Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict input to 5 characters if whole number or 8 characters with fraction

I have simple text input:

 <div style="float:right" class="xField">
      <input id="userLength" name="userLength"/>
      <label style="margin-left: 3px;">m</label>
 </div>

I need this input to only accept numbers and if the number is a whole number, it should only allow 5 characters i.e. 12345. If the number includes a fraction, it should then allow for 8 characters i.e. 12345,99.

I've tried adding maxlength to the input but that only works with one of these conditions at a time.

How can I accomplish this?

like image 625
Henrique Tavares Avatar asked Dec 12 '19 20:12

Henrique Tavares


People also ask

How do you restrict characters in input?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I restrict only input numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.

How do I restrict a textbox to accept only numbers in Javascript?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I allow only numbers in angular form field?

Allow Only Numbers in Angular Form Input For handling only numbers in the input box we simply add an input control with the ( keypress ) event handler to call the keyPressNumbers() . Below is the code snippet for this along with the output. You clearly see that only numbers are present in the input box.


1 Answers

You could use the pattern attribute and provide a regular expression that supports your requirements.

for example (this does not forbid entering invalid data, but will mark the field as invalid while the pattern is not matched).

<div style="float:right" class="xField">
      <input id="userLength" name="userLength" pattern="\d{1,5}(,\d{1,2})?" />
      <label style="margin-left: 3px;">m</label>
 </div>
like image 124
Gabriele Petrioli Avatar answered Oct 01 '22 15:10

Gabriele Petrioli