Parsley.js - Validate optional input for only numbers
Asked Answered
M

1

12

I have a form that has one optional input and 3 required input fields. For the optional input I have the below markup:

<input type="number" placeholder="0" min="0" max="20000" step="100" data-parsley-validation-threshold="1" data-parsley-trigger="keyup">

This does not fire the validation if I have type in letters or any other characters. It does validate for min and max values. If I put required attribute it does seem to work but I don't want that. I also tried defining a pattern as below:

data-parsley-pattern="^[0-9]*$"

None of them seem to work. Any ideas?

Medor answered 6/12, 2014 at 23:9 Comment(2)
To clarify, you want the field to be optional (so, the field can be empty). However, if the user sets some value you want it to be integer. Is that it ?Ulphiah
@milz Yes that is correctMedor
V
24

You can use data-parsley-type="digits". Notice the use of type="text" instead of number.

This works if you only want to allow digits (not floats).

<input type="text" placeholder="0" min="0" max="20000" step="100" 
    data-parsley-validation-threshold="1" data-parsley-trigger="keyup" 
    data-parsley-type="digits" />

If you want floats, you can use data-parsley-type='number':

<input type="text" placeholder="0" min="0" max="20000" step="100" 
    data-parsley-validation-threshold="1" data-parsley-trigger="keyup" 
    data-parsley-type="number" />
Vanna answered 12/12, 2014 at 12:48 Comment(8)
This seems to work but what if I need to accept floating values as well? like 10.5?Medor
@Medor I've updated the answer to allow floats.Ulphiah
This apparently fails HTML validation cause I have type text and then min max attributes. Also doesnt show the increment/decrement functions. For eg: cl.ly/image/2P0k3H3W0S2r Any remedy? Thanks in advance ;)Medor
Uhm... I'll have to take a look at the regex that Parsley is using. I'll let you know when I find a solution.Ulphiah
@Medor It seems that's a Parsley Bug. If you take a look at Parsley.js source code, around line 1681 is where it will add number or integer constraint. So far so good and the both use Regex. The Regex validation is performed on line 758. Now the issue is that the regex is only performed if you already have an integer / float. If you have a string there's no Regex.test(). I couldn't find the cause to this, but you might want to file a issue on GitHub.Ulphiah
As a workaround, you might want to use Parlsey with a Numeric Validation Plugin (like this). Nevertheless, it would be better to fix it directly in Parsley source code.Ulphiah
Note there is a typo in the first line of the above answer. parsley is spelt incorrectly. Just mentioning in case anyone else copied and didn't immediately notice (like me)!Vacillation
@Vacillation Fixed it. Thanks.Ulphiah

© 2022 - 2024 — McMap. All rights reserved.