46 ms·
The number input is the worst input
- padseeker 4y agoFYI - I wrote the article, happy to answer any questions
- withinboredom 4y agoI think you’ve missed a few things. - not everywhere uses a decimal, some uses the comma and a decimal for thousands. Using a number input, these things are handled for you. - this seems highly specific for a SPA and not server-side - “e” is a valid part of a number, I don’t understand why you have issues with it.
- padseeker 4y agoJust read the article. A big part of the article that I can summarize is I don't set the requirements, someone else does. Every project is different. You might be fine with just integers. However I've been tasked with much more complicated requests. There may be exceptions but I guarantee you in most cases the product manager doesn't want the letter e. My app was built with Rails, and if you enter the value "3.9e3" which represents the number 3900, Ruby will simply use the number 3 and toss the rest of the value away. Do you really want to add special functionality on the back end to covert that value into the actual value? I surely would not. Also plenty of people use javascript without it being a Single Page Application. Keenforms is not a SPA, we use React for certain pages, but I wanted to keep server side rendering. Using Javascript is not exclusive to SPAs.
- avalys 4y ago3.9e3 is equivalent to 3900 in the same way that 3,900 is equivalent to 3900. So, Ruby’s number parsing is garbage I guess. Hopefully it at least does this properly for floats?
- padseeker 4y agoWith ROR it might be transformed via the params parser. If you enter the code below in plain old Ruby environment, like irl or the console, it will properly parse it; "3.9e3".to_f => 3900.0 Something happens when submitting web based params. I'd be curious to see what other back end languages and frameworks do.
- radiospiel 4y agoThis is what happens: "3.9e3".to_i => 3 and Integer("3.9e3") raises "invalid value for Integer()". Really, nothing to see here. Ruby just doesn't treat "3.9e3" as a valid string for an integer (which arguably is correct IMHO)
- Flimm 4y agoSome countries use a comma as the decimal point. So it's not obvious to everyone that 3,900 == 3900
- withinboredom 4y ago(int) ‘3.9e3’ gets parsed correctly in php, perhaps use a language built for the web and not a general purpose language, or a framework that knows how to parse exponential notation? It sounds like Rails doesn’t understand how software works. I’ve also been messing with forms for twenty-something years, and I’ve never run into these sorts of problems but I understand the problems you are facing, especially after googling these problems and their solution in regards to Rails. I’ve heard it’s a productive language, but when you have to solve such simple problems, maybe not? Sorry, I don’t mean to bash on your chosen language which is probably how this is coming across. I’m genuinely intrigued by these stack overflow answers.
- test098 4y ago"Completely change you application stack and learn a new language so you can parse 3.9e3" is not really an option for most people.
- padseeker 4y agothank you so much for this
- padseeker 4y agoJust because you didn't run into these problems doesn't mean they don't exist. The clients I do work for have very complicated requirements and expect a lot of dynamic interactions from the forms they pay for. It could be a non profit trying to determine if a new client's family qualifies for federal benefits based on family size and income level. It could be a gas pipeline company trying to calculate how much natural gas they can deliver on a 60 day contract during summer months versus winter months. It could be calculating the medication dosage per body weight for a pharmaceutical company. There was the life insurance example which I mentioned in the article. Ruby will parse "3.9e3" properly. However Ruby on Rails param parser tries to prevent bad data from entering the system. So the e gets sliced off. There are things that you can do to prevent data from being entered that way. However like I mentioned in the article and commented on multiple times its not always my choice. And overwhelmingly the product managers and stake holders I interact with would prefer to not see numbers submitted in scientific notation form. There's no reason why you would want to submit your age like that. It's highly unlikely anyone would need a product quantity value in that format. And maybe most importantly the people who pay tell me all the time they don't want it. Does that make sense?
- mmis1000 4y agoIf I understand correctly. JavaScript itself didn't even think '111,2' is a proper float number. Only decimal point is allowed. So by using it, your input already bugged out. The number input is just wild and it did not support transform the input to a proper number for you.
- rimunroe 4y ago> JavaScript itself didn't even think '111,2' is a proper float number. Only decimal point is allowed. So by using it, your input already bugged out. I may be misunderstanding the gist of your comment, but surely the only "bugged out" behavior would be to try and call parseFloat on the value of the input directly without accounting for localization. Why should JavaScript's number representation affect whether or not I can enter numbers in the way I do everywhere else? The browser offers an API[1] for displaying numbers in a specific locale after all, though it's annoying that you either have to hack something together using Intl.DateTimeFormat.prototype.formatToParts or use a third party library in order to parse them. [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- withinboredom 4y agoIf you use a locale where commas are decimals and use number input, it is a decimal in the code. I have my computer and phone set to en-NL, which has that style of numbers.
- jeroenhd 4y ago> to a proper number A proper number is 123.456,78 in large parts of Europe. If I can't put that into your number control when my browser locale is set to Dutch, your custom number input has failed as much at the broken input we're talking about. It's not just the specific separators, of course; in India such a number is often written like 1,23,456.78 for example, grouping numbers entirely different. Don't assume everyone is American.
- Svip 4y ago> Using a number input, these things are handled for you. That's not my experience. I used a number input field for actual numbers (i.e. amounts of currency), but on some phones (specifically Samsung phones), it would show up with a full stop for decimal points (even though the locale was explicitly set to one with commas for decimal points), and users were unable to enter decimal numbers on Samsung phones. Unfortunately, the handling of the number input field is extremely browser/OS dependent. Eventually, I decided to go for text input, with numeric for inputmode, and simply interpret both "." and "," as decimal points (not permitting the user to use thousand separators, but few people would do that for input anyway). A bit awkward, but it worked. Note: Using text and inputmode=numeric did not technically solve the issue of Samsung phones persistently showing the wrong keypad, but the JavaScript interpretation was the real solution to the problem.
- cronix 4y agoWhen you say "on Samsung phones" do you mean the native Samsung web browser, or any browser on a Samsung phone? Like does this happen on Firefox or Chrome on the Samsung phone?
- Svip 4y agoI will admit, my testing was limited to the native Samsung web browser and to a capacitor made native app, where the problem occurred. It is very possible that Firefox and Chrome on the phone would behave as expected, but I never tested them, since users were experiencing the problem with the other versions of the app, and I needed to find a solution. Initially, I thought it was a problem with converting a React app to a native app with capacitor, but I tried the same Android app on a different (non-Samsung) Android phone and it did not have the problem (iOS similarly did not have the problem, both web and native version).
- wongarsu 4y ago> “e” is a valid part of a number, I don’t understand why you have issues with it. I think people would have fewer issues with it if the browser transparently converted it, either on entry or when calling .value. It's a somewhat obscure case that's easy to get wrong. For example if I enter 104e4 into a number input with ID test, I get these results in Chrome/Edge: > $("test").value '104e4' > parseInt($("test").value) 104 > parseFloat($("test").value) 1040000 > $("test").value - 0 1040000 Same with decimal points. It's a weird foot-gun because the solution is only half-there.
- padseeker 4y agoIt depends on what you are using on the back end. So for the record my own app's back end is Ruby on Rails. If you enter the value "3.9e3" which represents the number 3900, Rails param parser will simply use the number 3 and toss the rest of the value away. Do you really want to add special functionality on the back end to covert that value into the actual value? Most of us would not. I'd be curious to see how other languages and frameworks handle this issue but the e for many of us is a real problem. Most people aren't even aware of it, and learn the hard way.
- kilian 4y agoIf you know you're dealing with a number, use `.valueAsNumber` instead of `.value`. Value is a string per the specification, but `.valueAsNumber` does what you expect (for datetime there is also `.valueAsDate`).
- Jasper_ 4y agoThe form is submitted to the server using `value`, not `valueAsNumber`. Or maybe you'd prefer all forms to be submitted using JavaScript instead of just using <form action>?
- runarberg 4y agoThat is up to the developer. Most devs I know prefer to intercept the submit event, convert the form to a JSON object and send the JSON to the server. However if you don’t want to intercept the submit event, then it is up to your server to parse the eccentric inputs, the browser will send them (almost) as is (almost, as in it will consider the locale, e.g. 13,37 will be sent as 13.37 for some locales).
- onion2k 4y ago- this seems highly specific for a SPA and not server-side How would you expect users to enter numbers on the server?
- withinboredom 4y agoform method = ‘POST’ and a submit button. Usually.
- anamexis 4y agoso... with a number input?
- cyral 4y agoA SPA is calling a backend as well... and the backend (SPA or not) still needs to handle the number locale (comma versus decimals), unexpected 'e', etc. Not sure what about this is a JS problem.
- withinboredom 4y agoFWIW, I’ve never seen an ‘e’ from a number input on the PHP side, probably because it is parsed correctly. I’ve also never seen it from ‘.valueAsNumber’ on the js side either, except rendering big/small numbers but the internal representation was still correct. Using IntlFormat solved that problem IIRC. If you are passing it around as a string, then I imagine it’s a bigger problem.
- jerf 4y ago'“e” is a valid part of a number, I don’t understand why you have issues with it.' That's a very programmer-centric take. A very, very programmer-centric take. The use of "e" for exponent in scientific notation is a very computer-oriented take on the problem. Such other places as you may have seen it used are leaks from the computer representation. Nobody else sees numbers that way; scientific notation is generally written as 3.278·10³⁶ (only with better superscripts), which is how it is taught in schools for the most part. There are many contexts where I would say it is not a valid part of a number, because I don't expect my users to know scientific notation, let alone an idiosyncratic rendering of it used only for historical reasons in certain niches of the programming world.
- withinboredom 4y agoI have used a calculator before, and I would expect most users to have used one before too.
- arjvik 4y agoEven within the privileged US, you can't expect people to remember obscurities of calculator notation.
- withinboredom 4y agoI’d hope so, it’s basically taught in the 2nd grade (group 4 here), along with how to read and write and it seems people still remember that ok. Google is also immensely helpful if people forget how to read numbers. /s I guess the point is, you can parse it and output it in whatever format is appropriate, regardless of how it is stored.
- outworlder 4y agoStates are also taught in schools and yet many people think New Mexico is outside the US. If you are creating software for engineers, that's a fair assumption to make (that will understand what an exponent is). The public at large? Absolutely not.
- blowski 4y agoKnowledge is knowing "e" is a valid part of a number. Wisdom is knowing your users probably didn't enter their phone number as a power of 10.
- LinAGKar 4y agoA phone number isn't a number, it's a string of digits. It should not use a number field. It's not even just digits, it can also start with +.
- xg15 4y agoThanks for the write-up. I'd be interested to know what the actual reasoning in the complaints were though that Keenforms does not use number inputs. Was it just standards pedantry or were there some actual usability issues that were caused by that descision? You mentioned inputmode="numeric" a few times as a possible solution. Does Keenforms make use of that?
- Karellen 4y agoCan you give an example of an invalid value in a number input that you can't retrieve, and explain how that's worse than the invalid value in a text field? I'm having trouble figuring out exactly what the problem is there. As for min/max limits being bypassed and needing to do server-side validation also... well, yes? But, don't you have to do that even if you're using javascript for validation? The user could modify the DOM directly and replace the form control with one of their choosing that doesn't have javascript listeners, or submit a request from the javascript console, or even figure out all the required cookies and everything and submit a request with arbitrary params using `wget`. The server must always validate client input.
- padseeker 4y agoThank you so much for asking so kindly. I'd actually be thrilled to do that. I built a form that gave a price estimate for a product, and it would change as you modified inputs on the screen. One of the requests was to treat a blank number input as a zero. That particular input was not required. The ideal situation would have been to default the number input to zero, but the product manager wanted to let the user leave it blank. The problem became evident when the calculations to generate the price estimate treated a blank value and an invalid number value the same. You always get a blank string whether its blank or an invalid number value. To be honest I really hate whoever made this decision with the W3C committee or whoever it was. It makes zero sense that you let a user put it bad data but you won't give the invalid value via javascript. This was a deal breaker. We had to switch to the text input. It should also be noted that the built in validation for the number input takes precedence over whatever javascript written to generate an error message. There were complaints from the designer about this issue. It may seem like a petty thing but again I don't get to make these decisions, they are made by the client.
- Karellen 4y agoSo, there's a number needed for a price estimate, but it's optional, and may be zero. I'm still having a bit of trouble here, but let's say it's "number of spare parts". That's a number that could be zero, but if it's more than that you need to charge the customer extra. Let's say each spare part is an extra $5, so if the user enters "1", that's +$5. and if they enter "4", that's +$20. If they enter "0" that's +$0. And if the user enters "quux", that comes out as a blank value, so you treat it as "0" and modify the price by +$0. Which is...fine? What extra price did you want to add to the calculation if the user requested "quux" spare parts? Does anything else even make sense? If you need to tell the difference between an invalid value and a blank string, you should be able to use "checkValidity()". Sure, being able to retrieve the literal invalid value might have been nice to have in some ways, but I can't figure out why not being able to get it is a blocker for using the "number" type at all - even with the requested design constraints.
- pxeger1 4y agoIs this an advert for Keenforms?
- padseeker 4y agoI'll admit I name dropped my own product a lot. As a programmer I'm a little embarrassed, bordering on shameless. But as a single founder it means I have to do marketing, which means I have to be a little shameless.
- hn92726819 4y agoDoesn't using the gov.uk article work fine for issues 1, 2, and 4? <input required type="text" inputmode="numeric" pattern="-?[0-9]+" title="Integers only" /> <input required type="text" inputmode="numeric" pattern="-?([0-9]+|[0-9]*\.[0-9]+)?" title="Decimal numbers only" /> <input required type="text" inputmode="numeric" pattern="[0-9]*(\.[0-9]+)?" title="Positive decimal numbers only" />
- kilian 4y agoMy personal pet-peeve is devs using the number input for things that contain digits but aren't "numbers" (credit card numbers, 2fa codes, postal codes etc)[0]. Number input provides a lot of footguns and you're usually better off using something else. [0] https://kilianvalkhof.com/2022/css-html/are-you-sure-thats-a-number-input/ https://kilianvalkhof.com/2022/css-html/are-you-sure-thats-a...
- madeofpalk 4y agoThe most infuriating part about number input, is when you set min=0, you can't backspace in the field to enter a different number.
- Zardoz84 4y agoI don't see that behavior on Firefox and Chromium ... What browser dos that ?
- padseeker 4y agoI actually mentioned that at the bottom of the article on how to handle the issues mentioned. Firmly agreed, using the number input for non mathematical values is a horrible idea.
- xxr 4y agoA former employer had a system that consumed phone calls from Twilio. The phonecall table had a touchtoneinput column for the sequence of digits a caller pushed after the call connected (press 1 for English, press 3 to dispute a charge, etc.). We would sporadically get these query errors on inserts--turned out the touchtoneinput column was defined as a bigint, and the rare occasions where a caller pressed the # or * keys were sending input that obviously could not be parsed as an integer. Good rule of thumb: if a reasonable person calls it a number, but your application is never going to perform arithmetic on it[0], it should probably just be a string. [0]: Yes, a credit card number can be checksummed, but that's more in the sense of a CC# being a sequence of numbers rather than one int.
- 4y ago
- swlkr 4y agoI just ran into this, I thought it would be nice to use a number input for relatively large numbers in a form, but then a user asked for a thousands separator. I ditched the number input.
- ramesh31 4y agoThe (new-ish) ‘Intl.NumberFormat’ API solves this issue https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- crooked-v 4y agoNo, it doesn't. You can't apply that to a number input.
- runarberg 4y agoIt can, you just have to mask the input somehow (which can be very involved). In particular you would use numberFormat.formatToParts() and then add the parts to as the mask element interacting differently based on the type.
- sixstringtheory 4y agoI would not provide the user the ability to type a separator, but rather keep their number formatted with them in the appropriate places.
- lewisl9029 4y agoYep, this is known as input masking, and I wish browsers would just natively support this through various input types, because it's been the bane of my existence. Phone inputs are especially painful to mask since you have to deal with a mind-boggling number of format variations.
- jen20 4y agoAlthough I agree with the point made in this case about the number input (provided "inputmode" is set so a mobile device presents the right kind of keyboard), this kind of thinking drives me nuts: > As a programmer, you might find this acceptable, but there’s a good chance your designer and/or product manager will not. I couldn't care less if a designer is unhappy with the native functionality my browser exposes, it's called a user agent for a reason. They probably aren't happy with my custom style sheet either and this idea that designers' whims can override user preferences needs to stop.
- barneygale 4y agoBizarre, isn't it? The goal seems to be to rely entirely on Javascript and throw away any native OS/browser handling. If your designers/product managers are asking for that it's time to find another job.
- ryandrake 4y agoSometimes when I want to depress myself, I try to imagine the total collective engineering-hours ever wasted re-implementing standard OS or browser controls, just because a designer did not like the aesthetic choices of the OS or browser vendor. When I think back to the least intrinsically rewarding programming tasks I've ever had, they were all along the lines of "XyzOS's combo box drop-down is ugly. Here is a Photoshop of how we think a combo box should look. Go write 10K lines of code to re-implement the functionality we could otherwise get with one line."
- spookie 4y agoI totally agree with you. I guess most non-programmers would roll their eyes reading this, but honestly, stop trying to make every single web page a native app replacement. And it's nuts how far we've gone into this. Companies don't want you to run their software natively, which is fair enough. But, somehow THIS is the best anyone comes up with. It's really, quite a sad state of affairs.
- esrauch 4y ago
- ffhhj 4y agoAnd the search input doesn't allow disabling auto-uppercase.
- bgro 4y agoThis sounds like victim blaming devs for correctly calling things numbers, but the expected correct answer is something else. There shouldn't be a guessing game as to what the most correct name is that causes everything else to be wrong. The true fault here is ambiguous naming conventions that become booby traps. Should we be blaming people for trying to pull open a door that has a pull handle even though there's technically "push" writing on it? It's just so convenient, as the door maintainer, to have just one type of door, though. Am I so out of touch? No, it's the users who are wrong! Aside from redesigning a lot of things like this that could've been implemented better, we need to do better to avoid ambiguous naming. We should adopt more verbose naming standards. In this case, we could get rid of literal "number" to replace with "number-incremental," "number-money," "number-scientific" etc. If people try to use just "number" and see it doesn't work, they should be able to quickly find the correct thing without having to decipher a made up nonsense name like "lambda" or scrolling through an alphabetical list of input types and having to spot every possible number type, read its description, and then compare every result to determine the actual correct one. Yeah, developers can learn with time and it's good to know all the different options... But why aren't we setting people up for success in the first place?
- r-w 4y agoTake it up with the way web standards work.
- ClassyJacket 4y agoThat appears to be exactly what they were doing.
- pavlov 4y agoThe number input should have been called “scalar stepper”. It’s genuinely useful when you have a scalar parameter and want the user to be able to increment and decrement the value with a given step.
- marcosdumay 4y agoThat thing is called a "spinner" almost everywhere. And yep, "stepper" would be good too.
- chadlavi 4y agoMeanwhile in ecom sites where there's a use case for this (how many do you want to add to your cart?) it's always just a dropdown anyway.
- LoganDark 4y agoI usually see it referred to a "stepper" or a "spinbox". Yes, a spinbox! http://bucarotechelp.com/design/htmlref/81042102.asp http://bucarotechelp.com/design/htmlref/81042102.asp
- silvestrov 4y agoThere should be seperate types: <input type=integer> <input type=float> We need 2 different input keyboards on mobile: it should not be possible to type a dot if the input must be an integer. Currently seems to difficult to get a simple integer input: Chrome and Safari does not interpret step=1 as "no decimals". Also: the up/down buttons should go. That should be an explicit option as they don't make sense in most cases. Might have a type=count for that.
- lazide 4y agoAlso fixed precision (aka currency) values.
- silvestrov 4y agoMight be woth having a <input type=currency currency=DKK> so the keyboard input can clearly show the currency that is entered. This can be very important in multi-currency applications, e.g. travel (both customer and admin). Currency attribyte is ISO code: https://en.wikipedia.org/wiki/ISO_4217 https://en.wikipedia.org/wiki/ISO_4217 Also: <input type=count> which shows up/down arrows, and is a special case of <input type=integer>
- lazide 4y agoThat actually sounds like an idea whose time has definitely come. Anyone here on the HTML standards body (or works for Google in the requisite part of the Chrome team)? There are other uses for fixed precision besides currency (co-ordinates, tolerances, etc.), but currency would be used a LOT!
- jaywalk 4y agoVery good summary of the issues I've found with it as well. I've had to instruct my developers to never use this input type, and use an Angular directive to limit input values instead.
- hebrox 4y agoI was just looking into this today. iOS shows a decimal separator (a comma in the Netherlands) with `inputmode=decimal` and none for `inputmode=numeric`. You can try it out here: https://output.jsbin.com/necuzoj https://output.jsbin.com/necuzoj
- Minor49er 4y agoA lot of confusion around this is because there isn't a general understanding around whether <input type="number"> represents a strict numeric value or if just the input interface should be a numpad instead of a full keyboard
- deleted 4y ago[deleted]
- brundolf 4y ago> The Gov.UK article mentions a possible solution: Using <input type="text" inputmode="numeric" pattern="[0-9]*"> is a nice option for integers, but it won’t work for floating point decimal numbers. Note that there's also an inputmode="decimal" option which does have a decimal-point on Android and iOS Really the answer is just, "don't use number most of the time, use regular text with the appropriate inputmode". The inputmode abstraction is better than the type abstraction; it lets you specify what you really care about most of the time (mobile keyboards) without a bunch of extra constraints bundled in there
- darepublic 4y agoUpdating pattern to support float seems viable no?
- brundolf 4y agoYep you can do that alongside this change
- onei 4y agoNot being a front-end dev, it does seem trivial, but using [0-9\.]* means you can have 1.2.3. You can tighten that regex up, but I imagine that either doesn't fly with mobile keyboard hinting or screen readers trying to hint what a correct value is.
- brundolf 4y agoThis one works: `[0-9]+([\.][0-9]+)?` > I imagine that either doesn't fly with mobile keyboard hinting or screen readers trying to hint what a correct value is The `pattern` attribute isn't used for anything except validation as far as I know; the mobile keyboard at least is entirely driven by `inputmode` and/or `type`
- greiskul 4y agoDoesn't work with i18n (some countries use , instead of . as the decimal separator).
- deleted 4y ago[deleted]
- 6510 4y agoIt was a nice idea initially but implementation was rather dramatically more complicated than one would think (or at least than I thought it would be) The article mentions some issues but the most horrific one is missing: If you focus the input field, hold the pointer over it and move the scroll wheel the value is rounded off, increased or decreased. There are 2 gotchas here. Thus I found myself filling out a form that has to be filled out with the utmost accuracy. I look over the values again and again until the paranoia of potential financial disaster is sufficiently comforted. My eyes circle from field to field 6-10 times. (I'm never again going to make a mistake with this form ever again, enough is enough) I then scroll to the submit button. You can imagine what happens next, it involved a lot of adrenaline. One of the fields had changed, it was lower than before and everything behind the decimal point was unchanged. To make matters worse, I had no idea how this happened. Next time I check all the values 20 times, scroll to the submit button and check the visible values again. So far so good? I keep doing this and eventually it happens again! It wasn't until the 5th time I finally deciphered what was going on. https://jsfiddle.net/d63gv41k/ https://jsfiddle.net/d63gv41k/
- banana_giraffe 4y agoThe suggestion about using pattern="[0-9]*" will cause problems if your users copy-n-paste (or just type) a number with thousand separators. People are probably used to providing input in a way to make the stupid computer happy, but that friction need not exist.
- m12k 4y agoI ran into an annoying limitation of number inputs. I want to create an input where users can step up or down by 0.5 at a time. And I want to make it so that if the number starts out as something that does not divide by 0.5, clicking the step buttons will first round up or down to the nearest multiple of 0.5. Well tough luck, that's not possible. If the number input starts with the value 0.01 and a step of 0.5, then 0.0 and 0.5 are not valid inputs, -0.49 and 0.51 are. And if I instead change the step to 0.01 to make sure 0.0 and 0.5 even become valid inputs, then the steps are super small and inconvenient for my use case, basically forcing the user to type the number instead of using the step buttons.
- runarberg 4y agoI had a similar issue sometime when I wanted the field to increment in powers of 2 (2, 4, 8, 16, 32, etc). I think the best way to go about it is to create custom spinner buttons which increments and decrements according to your rules, and then use the constraint validation api to set the more restrictive validity if the user inputs a value using the keyboard.
- headsupernova 4y agoa fun one I've found is that the Samsung keyboard on Android won't let you input negative numbers... they just omitted (-) entirely from the layout.
- psadri 4y agoHTML inputs have APIs for checking their validation state. The input returning "" in invalid state is easy to test for: const num = numInput.checkValidity() ? numInput.value : 0; // or some other default
- ajhurliman 4y agoThe stepper buttons on the number input are infuriating. They're far too small for anyone to click on, nobody uses them, and they look bad. Invariably, a designer/PM/someone will come back and say "Is there any way we can get rid of those stepper buttons on the right?" and then it gets changed to a text input with JS validation.
- Macha 4y agoAs are the associated change on scrolling behaviour. I keep finding myself adjusting number inputs when trying to scroll the page they're on.
- akira2501 4y agoYes.. but it is connected to Up and Down arrow. When you're trying to build a fast keyboardable UI, I've found it a convenient enough mechanism. Also.. to this authors point, wouldn't you just use the 'validationMessage' if you're trying to extract the cause of the error from the field. I have yet to find myself in a position where I need the invalid value anyways.
- sedatk 4y agoThey probably have an entirely different UX on mobile too.
- ajhurliman 4y agoDon’t get me wrong, I love the arrow key functionality and I want to make it accessible, but the lack of ability to suppress the stepper buttons kills it for me
- montag 4y agoThis has got to be some kind of vestige from Windows 3.11, when the spinner control was about 3x larger - relative to the common screen sizes of the time, that is.
- aasasd 4y agoI'm baffled as to why in all these years no one just changed them into a pair of diagonally-separated buttons, and increased the width a bit. This would look a little awkward in the world of rectangular everything, but eh. The whole shtick with their size is that they're made to equal the input's height. Alternatively, of course, custom forms just make the buttons full-size, and I'm pretty sure they could be positioned next to each other: https://i.stack.imgur.com/IHqmt.png https://i.stack.imgur.com/IHqmt.png
- calyth2018 4y agoYeah no. Drives me nuts on the phone when people don't use the numbers field, so the VKB is not in the number pad mode automatically. A QWERTY vkb in numbers / symbols mode have tiny number keys compared to a number pad. If browsers validate differently, then fix them.
- 0x457 4y agoField type and inputmode are different things. You can have text field, but with numeric keyboard. Which you would know if you read the article.
- deleted 4y ago[deleted]
- tuckerpo 4y ago> Imagine a software tester finds this issue and logs a bug. Imagine the product manager hears about the bug. Imagine discussing this bug during sprint planning, but then pleading your case to that same product manager: “This is an edge case and the number will still be validated on the back end.” And besides, you said this was MVP and this “bug” is actually standard behavior of the number input. Imagine losing that battle and having to fix it anyway. I felt sick reading that. We've all been there.
- runarberg 4y agoIt is actually very common to intercept the submit event and do cleanup on the frontend, it is basically the default behavior for all modern frameworks. And if you do that, you can do nice things like submit a proper JSON (e.g. { "number": 42 } as opposed to { "number": "42" }), or use `inputElement.valueAsNumber` to let the browser handle all the oddities of typing a number in a localized way.
- AtNightWeCode 4y agoFrontend problems really are something else. First, a number may include letters and does not correspond to real numbers. Second, JS thought it was a good idea to not care about the datatypes. Then the worst. The mess created by decimals and commas having different meanings in different langs and cultures. A bug I see a couple of times per year and a freaking terrible one cause users enter decimal numbers that are 100 times smaller or bigger than intended.
- partdavid 4y agoThe article lays out a lot of good points, though I think a lot of them can be summarized more as "here are things you may not have realized about the number input, so use it accordingly" rather than "it's the worst." > The built-in validation is visually inconsistent to whatever UX when you are building for your app. To me, this is the kind of thinking that takes Web 2.0-isms too far and makes for actually really shitty UXes. (And yes, of course, I know that the responsibility for these peeves lies with product managers, designers and the like _as well as_ developers). I do not need a picker to pick my state. I know what f---ing state I live in. I do not need to review a list of all states, hoping I'll know it when I see it. In fact, for a semi-structured and rather complicated piece of data like an address, why force the user to partial-parse it anyway? No, the fact that you can type the first letter does not help. Just let me type the abbreviation. I know what it is! I f-----g live here! I know how to type a g-----n address, especially my own, and it's likely that, unlike you, I actually know how to do it correctly. You know, where my ward goes? Ward? You didn't think of that? My fractional street number or the fact that I don't have one? I do not need a calendar widget to pick my birthdate, especially when the calendar invariably starts with today and does not offer a straightforward way to type the date in my local format. I know when I was f---ing born. I do not need to look at a calendar and think "Hm, I know it was a Wednesday... maybe some time in the '90s? Better click the tiniest f---ing left-guillemet « I've ever seen 360 f---ing times and then maybe one of those months will ring a bell!" And also, run your braindead validation when I'm well finished entering my information. You do not need to red-highlight the field just because I put the point somewhere else outside of it. You do not need to give me a popup for every number in my phone number until there are ten digits. You do not need to confuse me by sometimes filling in phone number delimiters as I type, and sometimes prohibiting them from appearing at all. I've had two different phone number fields on the same form behave in both of these ways! Thinking of form-filling-out as a "user experience" or "live interaction" is okay, I guess, but it can't dominate your thinking to the point that you lose why it's a "form" in the first place. There are lots of use cases that really are analogous to filling out a form, I think a lot of web sites could do a better job of keeping the power of that analogy and using dynamics to enhance it.
- aasasd 4y agoOff-topic, but why am I confirming my nonchalance about cookies on Stackoverflow/Stackexchange sites like three times every week? The first bunch of times I could handwave it off as a result of Stackexchange having hundreds upon hundreds of sub-sites, but that doesn't work months into the deal. It's not like I'm on a mission to visit all those sites.
- tommica 4y agoYou want a real challenge? Build a number input that handles localizations, some countries use "," to separate decimals, and allow displaying thousand seperator automatically while typing, but read the value as a normal number during submit. So something like "12.400,56" turns to 12400.56 and vice versa. Also, is it just me or does this article seem to be a bit of an ad for "keenforms"? Its mentioned multiple times.
- jdthedisciple 4y agoSounds like a problem that should've been solved once and for all already. To your last point: I think it more or less obviously is an ad for keenforms, yes.
- unnouinceput 4y agoYou don't handle localization in the field directly. You let it be "text" and ask your preferred library (which is built by people smarter than you/me) to convert said text to valid number. If it converts then good, now you have a number variable in memory with which you can do whatever. If it fails you pop-up the error message and ask the user to enter a valid number. I find on the fly correction (don't let user type letters, ignore signs, etc) to be confusing to end-user.
- aasasd 4y agoThe worst number input that I've seen is some Windows input, in which the value must always be valid and in the allowed range. So, say, the current value is ‘300’ and you want ‘100’—but you can't backspace over the ‘3’ and enter ‘1’. If the value is ‘350’ and you want ’100’, you can't even select ’35’ and type ‘10’, because the input will freak out midway and immediately replace the value with the allowed minimum. Moreover, how do you even type the number you want if the input can't be empty? If the minimum is 20, you can't ever type anything from scratch without doing some select-replace gymnastics, because every digit will be immediately replaced with the value 20. Can't remember which app it was, and if it was a standard input from one of the dozen MS frameworks—but the testers on it must've been mightily incompetent. Imagining for a second that someone worked on that is like catching a glimpse into an abyss of pure stupidity. After this horror I'm quite relaxed about problems with inputs that at least allow me to type the damn number.
- nijave 4y agoReminds me of the inputs that try to be clever with formatting and move the cursor around and insert characters (happens with dates a lot). When you try to backspace, the input cleverly re-inserts the divider and moves you forward again
- temp_account_32 4y agoYeah this does sound very user unfriendly, although I have to say a good validation UX is particularly difficult to code (When to validate, on submission or on losing focus to that element or instantly on input? Do you need to debounce the validation? How to present validation error messages and where? Etc.). Your example probably stemmed from the case that the developer wanted the user to have instant feedback on validation, and instead of displaying some validation error message next to the input, they decided f-it - let's just immediately validate on input and not allow any invalid input. Bad/lazy decision, but I can see how it came to be.
- montag 4y agoI accidentally implemented this behavior in a number input recently. Felt stupid after fixing it. This stuff can happen so easily when people don't use the stuff they build.
- jiveturkey 4y agoreally nice ad for Keenforms!
- aarongray 4y agoCase in point: https://stackoverflow.com/questions/6178556/phone-numeric-keyboard-for-text-input/31619311 https://stackoverflow.com/questions/6178556/phone-numeric-ke...
- bob1029 4y agoIf a non-developer calls it a "<something> number" it's definitely a string for me. Even if you need to occasionally perform arithmetic on these "numbers", you could still store them as strings and parse on-demand. In my experience, performing a culture-specific decimal.TryParse() at form submission time is the most robust way to validate something like a wire transfer amount. You can also do regex replace javascript stuff, but there are always some dragons in that realm (especially as you cross borders). Your backend is almost always going to be a better place to parse and verify user input.
- runarberg 4y ago> I won’t pretend to be the expert on all things related to forms Indeed. All of the issues the author is experiencing can be easily fixed with simple and readily documented javascript methods: > When the number input contains an invalid value and you retrieve the value, you get a blank string > Valid numbers include more than just digits (i.e,. scientific notation like the letter e). > Different browsers accept different characters Use inputElement.valueAsNumber and stop worrying. If you send the form unaltered (that is, without intercepting the submit event), use a custom validator. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputEl... > Min/max limits can be bypassed Use frontend validation, e.g. inputElement.validity https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Constraint_validation https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Cons... There are plenty of weird form elements out there, but input type=number is actually one of the better one. But the author is definitely very right about one thing: > You should only use the number input when dealing with mathematically relevant numeric values Mathematically relevant might be to strict. I would say that if ordering the numbers makes sense, then input type=number most likely makes sense as well. If your data is simply represented by a number (e.g. zip codes; 90210 < 98112 is a weird statement) input type=number is the wrong choice.
- padseeker 4y agoThere have been requests for functionality to use an inputs value for a calculation, like for a price estimate. The requirements were also for a blank input to be treated as a zero. Because of the invalid value returned as blank there is no way to make the distinction between an invalid value and a blank value. The valueAsNumber will return NaN for a blank value or invalid. The fact that the DOM API returns a blank value for an invalid number is a massive misstep on the part of whoever makes the decisions surrounding the DOM API. The W3C? Whatever, this is a truly awful decision. I don't know pretend to be the expert. But I've seen a lot of things, and I've learned a lot over the past 15 years. For certain requirements there is no way to clear this problem.
- runarberg 4y agoSeems pretty clear cut for me: const value = input.value ? input.valueAsNumber : 0; Or if you want to be super defensive: const value = Number.isNaN(input.valueAsNumber) ? 0 : input.valueAsNumber; The nice thing is that constraint validation will not validate empty inputs unless you put the required attribute on the input. However if it were me, I would default the input field to 0 (as in <input type=number value=0>) so that most users wouldn’t be confused by an unexpected default behavior.
- efitz 4y agoLet’s throw the baby out with the bath water. Highly specific types are very useful on screen-limited mobile devices as they allow software developers to implement very specific controls for them. It ticks me off that now I have to lose my 10-digit input keyboard for these fields and have to use the tiny on-screen keyboard for everything. Reading the article and the linked UK.gov article, it seems like there are two issues: (1) lack of more specific types leading software developers to (2) make bad decisions related to the number type for things that are numeric but not countable numbers. How about we just add a few specific types, or a subtype mechanism. Eg specific types for dates, PINs, and so forth. We would also need to add either a non-countable number type or a subtype of the existing number type. Under the hood it could even just be implemented as a string limited to digit characters, and would be usable for zip codes, etc.
- thayne 4y agoSome of these problems could be solved by having frontend validation on a number input. Regardless, I think the award for worst input goes to "datetime-local". The MDN page for it even says "Because of the limited browser support for datetime-local, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own". Followed by the date and time inputs, which are a real pain to work with.
- talim 4y agoIt also responds to the scroll wheel in some browsers, which sounds like a nifty feature except that we started receiving sporadic complaints and bug reports from users who insisted that forms were being submitted with slightly incorrect numeric values. I spent an embarrassingly long time trying to track down some bizarre number parsing bug or obscure culture-specific behavior before realizing it was actually just users' cursors being over the number input while they tried to scroll, causing them to inadvertently change values just before submitting the form.
- rjmunro 4y agoAbsolutely. The scrolling behaviour is the worst part about number inputs. I don't think I've ever found a case where it is useful.
- kashug 4y agoOften when I use number-input it's because I want numerical keyboard when people interact with it on a smartphone. Yes, input type="number" is not the best, but when I ask for 2FA codes or credit card number a metric keyboard makes sense. And this is currently the best way I know to achieve it.
- lucas_membrane 4y agoThe screenshot of this article contains an interest rate input field. The prompt in that field says "enter the interest rate, i.e. 3.25." The use of 'i.e.' (Latin id est, meaning 'that is') is a common error in such prompts. I think they meant 'e.g.' (exampli gratia) meaning 'for example.' That aside, the presence of the decimal point raises four somewhat problematic questions: (1) how many decimal places are you going to allow on input? (2) how many decimal places will you display back to the user after they enter more decimal places than the typical user is expected to enter? (3) how many decimal places of the input will the application actually use in such cases? (4) How wide do you make the field to display the interest rate, and what do you do if the user enters something that won't fit there? If you are writing software that should match the practices of more than one financial institution (bank, finance company, insurer, brokerage house, auditor, government regulator ...), the answers to those questions may be all over the map, and the number input widget probably will make it all an even bigger mess.
- deleted 4y ago[deleted]
- throwaway1851 4y agoI’m surprised at how bad native widgets are in general. They’re inconsistently styled, ugly, hard to override, and not all that usable. It’s nice that they have built in a11y support, but that’s about all they’ve got going for them. I wish there were a web standard for modular, customizable, styleable inputs and pickers. It would eliminate a lot of needless wheel-reinventing and also make the web more accessible.
- deleted 4y ago[deleted]