Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 pattern match float and/or percentage

I'm working with form validation and want to use pattern attribute for validate the input field. The field has the following criteria:

  1. It must be a number (Integer or Float)
  2. Can allow up to 2 decimal point (e.g.: 100.24)
  3. Only one dot is allowed (e.g.: 100.25.35 is not valid)
  4. May end with a percent(%) sign (But not always necessary)

So what should be the exact pattern RegEx for that. I'm trying with the following code but how to implement the percent condition?

<input type="text" 
       pattern="[0-9]+([\.][0-9]{0,2})?" 
       title="This must be a number with up to 2 decimal places and/or %">
like image 285
Al Amin Chayan Avatar asked Oct 15 '25 05:10

Al Amin Chayan


1 Answers

You are almost there. Add %? to your pattern:

input:invalid {
  color: red;
}
<input type="text"
       pattern="[0-9]+(\.[0-9]{1,2})?%?"
       title="This must be a number with up to 2 decimal places and/or %">
like image 56
Salman A Avatar answered Oct 17 '25 20:10

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!