Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 - number regular expression

Tags:

html

I have got an input field called Fleet no.

I want to validate it using HTML 5 to only allow the input of digits to 5 digit max length.

I have managed to only input digits but it only accepts 1 digit.

I can't put more than 1 digit. This is what i tried to do:

<div>
  <label for="element_1">Fleet Number </label>
  <input id="element_1" name="element_1" type="text" maxlength="255" 
  value="" required placeholder="Enter Digits only" pattern = "[0-9]"
  title='Fleet No. must contain digits only'/> 
</div>
like image 585
munue Avatar asked Jun 02 '13 14:06

munue


People also ask

Can you use regular expressions with HTML 5 inputs?

Unlike the regular expression syntax used in programming languages, HTML5 does not require '^' and '$' to annotate the beginning and ending of values (it is assumed). Regular expressions can be enforced on inputs by using the “pattern” attribute.

How do I create a regular expression in HTML?

The pattern attribute specifies a regular expression that the <input> element's value is checked against on form submission. Note: The pattern attribute works with the following input types: text, date, search, url, tel, email, and password. Tip: Use the global title attribute to describe the pattern to help the user.

How do you write numbers in HTML?

The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed. min - specifies the minimum value allowed.


2 Answers

Just add the below oninput expression into your HTML tag. This will allow accepting the only numbers between 0 to 9.

This one also restricts accepting +, -, .(dot).

<input type="text" id="salary" name="salary" maxlength="3" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" />

'OR'

<input type="text" id="salary" name="salary" maxlength="3" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />

I found this in one of the js fiddles, and It works for me.

like image 168
TauFeeQ Avatar answered Nov 16 '22 01:11

TauFeeQ


Use [0-9]{1,5}

<input type="text" pattern="[0-9]{1,5}" />

{1,5} means repeat the previous part 1, 2, 3, ..., 5 times.

like image 36
Wouter J Avatar answered Nov 16 '22 01:11

Wouter J