3
votes

I have a form that contains this input field:

 <input type="number" name="price" data-bind="price">

And this knockout validation definition:

 ...
 price = ko.observable().extend({required: true, number: true})
 ...

The problem is that when I enter a non numeric value the browser actually sets the value of a type="number" field to an empty string (internally) so the model receives an empty string. Due to this the knockout validation mechanism always triggers the 'required' validation even though the user sees a value in the field. It would be better to trigger the 'please enter a number' message instead of the 'this field is required' message.

I could of course use a type="text" but that triggers the wrong keyboard on mobile devices. Any ideas how to solve this?

This is of course related to this issue: HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?, but using a type="tel" is not an option for me unfortunately.

1
hi @koenpeters Can't you create your own validators and pass call backs to display appropriate message? github.com/Knockout-Contrib/Knockout-Validation/wiki/….Rohith Nair
I ended up using type="text" with an html5 pattern: '\d+([,.]\d{2})?'. Not that nice, but good enough for what I neededKoen Peters
I am facing a similar issue with cordova+ knockout js. can you help @koenpeters : stackoverflow.com/questions/42736659/…Parth Doshi

1 Answers

1
votes

This is awkward, because as the answers to this question reveal, browsers do not expose the 'raw' text value of HTML5 numeric inputs, and return an empty string as the element value in the case of both invalid and null inputs. You therefore cannot reliably differentiate between non-numeric and missing values - which is ultimately what your error messaging requires.

You can't even sniff for keypresses and see if users enter invalid characters that way, because you don't know if users copy/paste invalid content.

In the past I have written custom bindings that create text inputs and coerce them to numbers, but these will have limitations like bringing up the wrong mobile keypad, as you acknowledge.

It's disappointing, but I can't think of a solution for this problem.