Parsley.js - Validate optional input for only numbers

user3312508 picture user3312508 · Dec 7, 2014 · Viewed 25.5k times · Source

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?

Answer

Lu&#237;s Cruz picture Luís Cruz · Dec 12, 2014

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" />