1

I have a select box which option contain Negative numbers, floar numbers. How do i validate that in parsely.

<select class="form-control"  data-parsley-pattern="^[0-9]*\.[0-9]{2}$" id="duration"  name="duration">
    <option value="-1" >Not Strated</option>
    <option value="0" >Just Strated</option>
    <option value="1.6" >1.6 % Done</option>
    <option value="2">2 % Done</option>
    <option value="2.6">2.6 % Done</option>
    <option value="3">3 % Done</option>
    <option value="3.6">3.6 % Done</option>
    <option value="4">4 % Done</option>
    <option value="4.6">4.6 % Done</option>
    <option value="5">5 % Done</option>
   //And So on...
</select>

I have tried some of solution on SO but it didn't work.

data-parsley-pattern="^[0-9]*\.[0-9]{2}$"

The Solution Which i found to validate negative and float numbers in parsley is.

^-?[0-9]\d*(\.\d+)?$
always-a-learner
  • 3,671
  • 10
  • 41
  • 81
  • I have never heard of parsley. But your regex seems to force two trailing digits. And none of your numbers have that. Try this and see if it works for you. https://regex101.com/r/i5qt3m/1 `^[-0-9]*\.?[0-9]$` – Andreas Jul 15 '17 at 06:51
  • @Andreas Sir you can add your suggestion to the answer, it is working. Thanks. – always-a-learner Jul 15 '17 at 07:06
  • 1
    Made some changes to it and added answer. Not sure which works best for you. I believe they are quite equal. – Andreas Jul 15 '17 at 07:10
  • @Andreas it is validating negetive number. can you please help to validate negative number – always-a-learner Jul 15 '17 at 07:19

1 Answers1

2

Your pattern was missing a few parts.
It did not capture negative numbers so I added a - in the first "group".
I added ? To make the float part not optional.
I moved . To the [ ] and added * to make zero or more possible.

^[-0-9]+?[\.0-9]*$

https://regex101.com/r/i5qt3m/2

OP found the answer: ^-?[0-9]\d*(\.\d+)?$

Andreas
  • 23,610
  • 6
  • 30
  • 62