46 ms·
HTML Form Validation is underused
- joshchernoff 2y agosimply adding required is all you need.Not required=true The omission is equal to required=false. No one really write required=true, they just add the attribute `required` only by its self. This is one of the odd quarks about html attrs Same is true for things like disabled ect https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HT... > The strings "true" and "false" are invalid values. To set the attribute to false, the attribute should be omitted altogether. Though modern browsers treat any string value as true, you should not rely on that behavior. in other words required=false may still end up making the field required. FYI.
- deathanatos 2y agoThey've written it in JSX, I think, not in HTML.
- Etheryte 2y agoThey've used `required={true}`, not `required="true"`, which is JSX, not HTML. The one with curlies isn't even valid HTML. In the old HTML spec, the correct value, if you wanted to set a value, was to set `required="required"`, but these days the spec is looser since it tries to conform to the web, not the other way around.
- joshchernoff 2y agoEven in jsx its not required to add a boolean value. Unless you are passing in a var as a prop in which case sure. But that didn't look like it was the case in these examples.
- ervine 2y agoOne of my favorite eslint rules to enable: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md https://github.com/jsx-eslint/eslint-plugin-react/blob/maste...
- everdimension 2y ago> Even in jsx its not required to add a boolean value Absolutely true! But I like to do it because I personally think it reads more nicely and is more explicit and that's what I do in all my projects. But it is indeed a matter of taste and I have nothing against code that follows the convention to omit the "true" value.
- donatj 2y agoYou gotta be careful about going overboard with it. Recently I was trying to get a refund on Groupon because the company I'd bought a Groupon for was under new management that refused to honor my groupon. The form had a stipulation "minimum of 15 words". Try as I might, I could not get the form to pass validate until I inspected the HTML. <input pattern="^(\b\w+\b\s*){15,}$" required> \w - word characters \b - word boundaries \s - white Literally zero allowance for any sort of punctuation.
- recursive 2y agoI don't think this is particularly pertinent to HTML validation. This is true of any type of validation. The same rule could have been applied on the server, and then you would have had no hope.
- whoisthemachine 2y agoExactly. My rule of thumb is "don't add validation until there is absolutely no better way and you absolutely must restrict this input."
- everdimension 2y agoThat's actually a good argument for the point I was trying to make. Existing validity attributes such as "pattern" are cool, but not enough. E.g. the "repeat password" example is actually achievable without "setCustomValidity" by using the "pattern" attribute. For that, you would have to dynamically construct a RegEx out of the value from the first input. I didn't want to make the article too long by comparing the solutions, but the point is, with the "customValidity" you see how much more eloquent and easier to read the validation is. So a nicer API here makes all the difference The "15 word minimum" constraint would look so much nicer as "value.split(/\s+/).length >= 15".
- jonathrg 2y agoThat's nice, I'll use that next time. Although it always feels kind of bad to write client side validation code because you're going to have to do the same checks on the server side anyway.
- recursive 2y agoDo you make your users do a server round-trip to see what's wrong? To have good UX, you kind of have to do both.
- dvdkon 2y agoI find it sad that so many frameworks leave the developer to duplicate server-side and client-side validation. There are obviously some things you can't reasonably validate on the client, but I'd like to see more automated ways to take backend constraints and check them on the client too. Ideally constraints would also propagate from model definitions, so there could be a single source of truth for "what phone numbers do we accept". Some years back I tried to do this by parsing SQL table definitions, but never got far enough. Django does this, but it lacks pretty much any client-side validation support IIRC. (Or client-side anything, really...)
- yen223 2y agoOne of the compelling reasons to use Javascript-based frameworks like nextjs or remix.run is that you can reuse the same logic + types on the frontend and backend. With Typescript, this is now my preferred way to build full-stack sites.
- cloudking 2y agoNecessary because a user can always inspect > modify the HTML.
- ervine 2y agoYou could use something like json-schema to define constraints, and use json-schema validator libs on the front and back end to validate the form data against the schema. You still need to handle the "what happens next" part on each side, but at least your validation rules are shared.
- Macha 2y agoOne of the things I dislike about HTML form validation is it starts running from page load. So if e.g. you tie error state formatting to it, the form loads up with a bunch of errors which may be intimidating to the user.
- sholladay 2y agoThis is one of the main reasons people started using JavaScript, to show errors only after a form has been “touched” or right before it is submitted.
- mattmanser 2y agoA bit perplexed by your comment. That wasn't a main reason people started using javascript. I even remember when people started evangelizing client-side validation in the mid-2000s. Javascript was already a normal tool used in web apps by then, and most web developers would regularly be adding javascript to their apps. Back then it was a bit of a pita as you had all sorts of gotchas with javascript memory leaks by registering change events on controls. I can't even remember the term now, but you could basically have a circular reference between a closure and a control and so it wouldn't cleanup properly. Also, modern developers probably can't even begin to imagine how slow javascript was on IE6. A loop of a few 100 iterations could bring it to an unresponsive halt.
- bryanrasmussen 2y agoprobably they mean why people started using JS in form validation, and not JS altogether, although agree that isn't the reason either.
- sholladay 2y agoCorrect, I meant that client-side validation driven by JS became popular because of UX issues when using pure HTML. There have always been plenty of other reasons to use JS with forms besides validation. But it’s notable because forms and form validation are such common building blocks that if people feel the need to use JS there, it kind of infects everything else around it. IMO, being able to build high quality form experiences without JS is critical to reducing bloat on the web.
- pbreit 2y agoThe biggest, easiest to implement underutilization is: "Using specific type attribute values, such as "email", "number", or "url"" These can significantly improve user experience on mobile by triggering the optimal keyboard.
- mattgreenrocks 2y agoIt’s amazing how many login forms are labeled “email” and then don’t have the correct type set.
- _heimdall 2y agoThis is particularly annoying on mobile since on-screen keyboards won't adjust to an email input layout and autocorrect will screw up basically any email address as soon as a "." character triggers autocomplete to commit it's guess.
- icar 2y agoAnd password managers will not fill in the credentials correctly.
- Sander_Marechal 2y agoGet a better password manager? I use Bitwarden and it has never failed to fill out the login forms for me.
- crabmusket 2y agoBitwarden has failed me on some sites.
- crabmusket 2y agoI think that in some cases this could be because the inputs accept usernames as well as emails. But not in all cases, which is annoying!
- wvenable 2y agoAfter reading all this, I think I'd still choose to do it away from the browser built in capabilities. I'd rather have full control over the process and the design than rely on the limited capabilities of browsers. The browser is programmable; at this point they should stop getting clever about adding built-in functionality and instead just expose better ways to use the browser as a dumb UI toolkit.
- Latty 2y agoCouldn't disagree more. Browser features can be much better at handling edge cases: disability, localisation, unusual devices, different input methods, weird screen sizes, etc... rather than hoping every developer does it right, building that in is more efficient and consistent. The common cases should be handled really well by browsers.
- wvenable 2y agoI couldn't disagree more; it might be good for disability but for localization, unusual devices, different input methods, weird screen sizes I have never seen that well executed by browsers. I almost always prefer a more full-featured alternative from a standard framework than whatever is lowest-common-denominator feature in a browser -- which also, depending on the browser, may or may not work the same or may or may not even exist. The browser should provide low-level capabilities and let developers build the high-level functionality from it. This article ultimately supports this by showing us exactly how half-baked this particular browser feature happens to be.
- JoshTriplett 2y agoBrowser functionality is typically (handwaving on exact numbers here) better than the worst 80% of sites, on par with the next 10%, and not as good as the top 10%. If you're putting in the effort to build a site in the top 10%, sure, you might not want to be "held back" by the browser. But the vast majority of sites would do better by using what's built into the browser. And I would argue that the value the user receives from that top 10% of sites is not commensurate with the pain the user receives from the sites that think they're in the top 10% but aren't.
- threatofrain 2y agoYa'll may want to checkout Valibot¹ or Zod² in conjunction with something like React Hook Forms³ or the more agnostic Tanstack Forms⁴. Really sweet form validation that's concise but as precise as you want it to be. The problem with vanilla form validations are (1) they're so basic that it's table stakes for any library or framework in this space, even ChatGPT can do it well, (2) there's an enormous amount of other validation scenarios they don't cover, and (3) unless your validation is simple and doesn't require a validation library, now your logic is split between two places. [1]: https://valibot.dev/guides/comparison/ https://valibot.dev/guides/comparison/ [2]: https://zod.dev/?id=basic-usage https://zod.dev/?id=basic-usage [3]: https://www.react-hook-form.com/get-started/#SchemaValidation https://www.react-hook-form.com/get-started/#SchemaValidatio... [4]: https://tanstack.com/form/latest/docs/framework/react/quick-start https://tanstack.com/form/latest/docs/framework/react/quick-...
- everdimension 2y ago> there's an enormous amount of other validation scenarios they don't cover Can you provide examples of those? Genuinely interested as I'm on a quest of creating a list of recipes that show that native form validation can be just as capable as custom validation libraries
- unlog 2y agoIn an all honest reply, is that the people that writes these specifications, live disconnected from the reality, they don't use the stuff they specify. That stuff works for very simple things, but then when your forms evolve you realise you will be better off just writing the whole thing yourself.
- jhardy54 2y agoYep. This is great until you need a cross-browser date picker, at which point you need to implement a bunch of stuff yourself. It’s frustrating how primitive HTML forms are, after so many years.
- kmoser 2y agoWhat do you mean? Most browsers support <input type="date"> natively just fine.
- lelanthran 2y ago> What do you mean? Most browsers support <input type="date"> natively just fine. The `<input type=datetime-local>` on FF has a broken time-picker[1], has always been broken, and there are no plans to ever fix it, ever. [1] In that it will let you pick a date, but not a time - the time must be manually typed into the input!
- francislavoie 2y agoWhat's hilarious is they do have UI for it in about:config "dom.forms.datetime.timepicker". It makes me so angry that it's not on by default. It works fine!
- cuu508 2y agoOn Android, the date picker widget is fiddly to use for selecting distant dates, like date of birth. Not impossible but requires many many taps.
- gunalx 2y agoI do get the point of using form validation clientside to ensure a better ui. But dont remenber to also verify serverside. Anything clientside can have been fumbeled with. (Also kinda anoying to have to duplicate this tho)
- Jerrrrrrry 2y ago> (Also kinda anoying to have to duplicate this tho) Security and convenience are like space and time, you can't move one without transformation of the other.
- woodpanel 2y agoYou could fill those setCustomValidity() calls in the client with rule-sets generated on the server. even re-fetch them from the server on each input change in the client or just ditch the whole thing and do it in htmx :->
- Jerrrrrrry 2y agoCould you not remove the event from the input change, replacing it with NOP? htmx looks dope af thanks
- yawaramin 2y agoOr do all of the above https://dev.to/yawaramin/handling-form-errors-in-htmx-3ncg https://dev.to/yawaramin/handling-form-errors-in-htmx-3ncg
- maxbond 2y agoI think it's a trilemma between security, convenience, and architectural sophistication (NB: I'm deliberately not saying complexity, because the code doesn't necessarily get more complex). It is usually physically possible to find a solution with equal security for a given level of convenience, but it will require an investment of creativity and possibly refactoring to realize. Both of those things are very expensive. To take an extreme example, you could ensure that validation happens identically on both the back and front end by writing your own framework with that property. You could create a framework with no more security bugs than the next best alternative and while providing great UX. But writing a framework and shaking out the bugs is a huge lift. So in practice you can't go all the way out on the third axis and it is approximately a dilemma. But if you're on the lookout for exceptions you may find an opportunity to cheat/curve bend (eg as suggested by other commenters, when using JS for the front and backend, you can use data modeling libraries like Zod to get most of the benefit for a fraction of the price of writing a framework).
- mannyv 2y agoThe real problem with client-side validation is you can't trust it. You need to revalidate on the server, no matter what.
- yjftsjthsd-h 2y agoIt's not a security feature, it's a UX feature.
- Jerrrrrrry 2y agoTrue, but if there's a communication bug between UX and back-end teams, that can escalate into a false sense of security and then an exploit.
- hn_throwaway_99 2y agoYou were being downvoted here, but I think you make a great point. The problem with having separate client-side and server-side validation logic is that you (generally) want the rules to be the same, but you end up needing to write them twice, usually in completely different technologies. I have seen many, many cases where the client-side validation and server-side validation got out of sync, and then just like you put it, obscure bugs or security exploits can arise from this. In general, I think client-side validation should really only be used for the basics, often with respect to type (e.g. the email/URL examples given) and just basic "required" (non-empty) fields. Anything more complicated than that should be done solely server-side in my opinion - e.g. I wouldn't use setCustomValidity with a complex set of client-side rules. What I think is important, though, is to ensure that if the server validation fails that the error message that comes back is not just a single "Bad input!" message, but errors can be keyed by field to ensure you can display field-specific error messages and error highlighting. Another option I considered back in the day when my backend was on NodeJS is to have the server return the text for a JavaScript validation function before the form itself is actually rendered. This, this function can be run client-side for immediate feedback when the user submits the form, but it's also the exact same logic that is run on the server when the form values are received.
- deleted 2y ago[deleted]
- 4rt 2y agothis is just react though. it's not HTML validation.
- everdimension 2y agoThe HTML is created using JSX, that's true. But the validation that the browser performs is part of the HTML behavior.
- DaiPlusPlus 2y agoLast time I checked, web-browsers today still do not allow you to style the appearance of built-in HTML validation messages [1]; this wouldn't be so bad if Chrome (and Firefox) still conformed to their OS platform UI guidelines (i.e. so it looks system-generated, like how `title=""` tooltips used to be), instead Chrome uses this ugly yellow/orange icon color with black-text on a white background on a bubble with a fixed corner border radius - it clashes horribly with my current project's aesthetics. [1] https://stackoverflow.com/questions/5328883/how-do-i-style-the-html-form-validation-error-messages-with-css https://stackoverflow.com/questions/5328883/how-do-i-style-t... Annoyingly, Chrome used to allow styling of validation-messages using vendor-prefixed pseudoelement selectors, but they removed that functionality and never brought it back; I'll chuck this on the same pile as other arbitrary annoyances like "can we have a native HTML combo-box please" and "why is <select multiple> still a horribly unusable ctrl+click box instead of a checkbox-list?".
- 354896547981565 2y agoTrue. But you can hide the default message and replace it with your own. You'll still benefit from the form validation.
- deleted 2y ago[deleted]
- jacobr 2y agoYou can even benefit from the default messages if you want that, grabbing `input.validationMessage` and rendering it as you wish.
- gregoriol 2y agoThere is no real benefit because the validation rules allowed there are often too limited for real use-cases anyway.
- epolanski 2y agoWhat do you mean there's no real benefit? You give the same error messages based on whatever custom validation and control the output.
- montag 2y agoIt's also easily misused. Take the regular expression validator for passwords on the California DMV website, for example. The website states "Must include at least 4 alpha characters". But the validation pattern ^(?=(.*[a-zA-Z]){4,})(?=.*[0-9!#$%]).+$ requires that these characters appear consecutively.
- deleted 2y ago[deleted]
- eddd-ddde 2y agoThe {4} is being applied to the whole group which includes a .* Isn't that correct?
- Izkata 2y agoYep, and the .* means "0 or more of anything", so it's 4 or more groups that each end with a letter. They can be consecutive or not and a group can be a single letter but doesn't need to be - so whatever the failure was, it wasn't that (or the regex was typo'd here to be correct instead of what was actually on the site).
- account42 2y agoThe regexp still requires four letters before the last digit or special character which is a weird requirement.
- GrantMoyer 2y agoThe (?=…) are "lookaheads". They match the enclosed pattern without advancing the cursor.
- everdimension 2y agoThat's exactly the case where the "customValidity" attribute shines! I have nothing against regex and the "pattern" attribute is the way to go for many cases, but having this is an alternative is also very nice: const valid = value.length => 4 && isAlphanumeric(value); return ( <Input value={value} customValidity={valid ? 'at least 4 alpha characters' : ''} /> )
- SahAssar 2y agoIt's a bit disappointing that articles talking about HTML use JSX/React syntax instead of actual HTML (even more so not actually saying it). Example from the article: <input required={true} />
- mcflubbins 2y agoI thought the same thing. I was once discussing a third-party integration with a React developer. The integration required that our app POST a couple of fields to the third-party's site. I found that the developer was struggling with the integration and they were asking me questions about it when I said something to them along the lines of "It's just an HTML form, with a couple of hidden inputs that when submitted make a POST request to this URL" they said to me "Yeah, well HTML is kinda old, it's not really used anymore"... I'm sure I've said plenty of stupid things when I was green but I hope no one remembers them like I remember this one. It lives rent free in my head.
- lelanthran 2y ago> they said to me "Yeah, well HTML is kinda old, it's not really used anymore"... > I'm sure I've said plenty of stupid things when I was green but I hope no one remembers them like I remember this one. It lives rent free in my head. I'm doing gigging while my product is gaining traction. Last week, I received this verbatim rejection for a PR review at a client, who's oldest developer is 27: "No, we don't want all the logic in the same place. You must split the logic up" This is also one that will take up valuable space in my head till the end of time :-( (PS. Yes, I split the logic so that it was evenly balanced in 3 different programming languages, instead of having the entire logic in C# alone)
- everdimension 2y agoIt's definitely true that many developers would benefit a lot from learning more about the basic HTML and the web platform. But I refuse to support the notion that this is somehow React's fault. In my personal experience, react allowed me to rely more on the native web platform APIs, not less, than other frameworks (at the time that I switched to react)
- wackget 2y ago[flagged]
- woodpanel 2y agoonce you grasp the ergonomics of setCustomValidity() you can go crazy e.g. pass it a multitude of validation rules per input field. unfortunately you’re sort of back to square one if you want to implement warnings (ie suboptimal inputs but still workable). Edit: While grasping the ergonomics produces euphoria like solving a complex puzzle it’s also a hint at the pain un-initiated colleagues will feel when tasked with maintaining the code.
- mcflubbins 2y agoIf you have a checkbox with a label, please a "for" attribute to the label so I can disable/enable the checkbox by clicking the label. This is one of my biggest pet peeves, maybe its just me.
- ozaark 2y agoNot just you it's a required feature of accessible sites following ADA/WCAG.
- wruza 2y agoWrapping input into a label also works. Not sure why people tend to separate the two. And also why browsers started separting these. It’s a checkbox and radio that should contain a text, not vice versa.
- pirate3215 2y agoOne reason I have heard about is implicit labelling doesn't work with all voice control tech, including macOS voice control[1] [1] https://a11ysupport.io/tests/html_label_element_implicit https://a11ysupport.io/tests/html_label_element_implicit
- stonethrowaway 2y agoNo it isn’t. It fucking sucks. Most everyone who learns HTML comes across the validation attributes, the god awful built in date pickers and other shit, and they throw it out in favour of custom built better UX implementations. Maybe in the past we would have been clueless because, well, they didn’t exist, but today they do. And they’re junk. Call spade a spade. Don’t call it heavily underused.
- nfw2 2y agoIt's extremely frustrating to me how reliably the anti-JS crowd on HN promotes this sort of "just use HTML / CSS" content. Having a general purpose programming is obviously beneficial for application development. There is no arguments to not use Javascript besides "some users (ie the people here on HN and virtually no one else) don't like to enable Javascript"
- jansommer 2y agoHtml form validation is great. There's just one gigantic catch: It doesn't work in Firefox for Android. https://bugzilla.mozilla.org/show_bug.cgi?id=1510450 https://bugzilla.mozilla.org/show_bug.cgi?id=1510450
- FrostKiwi 2y agoAs a daily Firefox on Android user, not catching up on standards is what hurts the most. Most painfully to me, all the WebGL stuff like [1] and some minor annoyances like [2]. Still, having uBlock origin among other extensions is a killer feature. [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1884282 https://bugzilla.mozilla.org/show_bug.cgi?id=1884282 [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1897707 https://bugzilla.mozilla.org/show_bug.cgi?id=1897707
- moron4hire 2y agoFirefox for Android has a smaller user base than Samsung Internet and Opera. It's 0.5%. It's a waste of time working on supporting it. Especially considering how little time people put into making sure their sites work for people using accessibility software. I don't think it's worth mentioning in these issues unless you're also ready to talk about UC Browser.
- makeitdouble 2y agoI wanted to quickly check the 0.5%, and see 1.2% in Japan for instance, where iPhone have near 80% share. https://gs.statcounter.com/browser-market-share/mobile/japan https://gs.statcounter.com/browser-market-share/mobile/japan That's still not a lot, but above 1% is a decent threshold to decide to support a browser.
- fortyseven 2y agoYay, I'm in the point five percent!
- johannes1234321 2y agoIs that somewhat biased? - I assume the number of people using Firefox has a quite big overlap with people using ad&tracking blockers, which block many statistic sites. (Website operators may log user agent which will be somewhat accurate still)
- temporallobe 2y agoThere’s a reason it’s heavily underused. So many frameworks and libraries provide robust, style-able validation capabilities, some with very sophisticated and extendable functionality. Don’t torture yourself if you don’t have to.
- dwg 2y agoAgreed. We try to use browsers standard features whenever possible. Despite looking into using the built-in validation, it's never been worthwhile. Too many gotchas, and we end up using a library to be able to easily support more complex checks anyway. Furthermore, using a library opens up, in some cases, the possibility of sharing some of the validation code between front and backend. In particular this article seems to work around one of the issues with `useLayoutEffect`. Not something that should be done lightly.
- mrweasel 2y agoYou also have to implement your own validation on the backend anyway. There's always going to be someone trying to fiddle around with your form, either using some weird browser, curl, or some other tool that doesn't have the same form validation built in. You're not going to trust that the client actually did the validation, or did it correctly, so the backend still needs to be able to validate input and show the form, with validation errors, on all fields. Frontend validation is only there to be helpful for the user, but if you can style it, or trigger it from the backend on submit, you have to implement your own styling anyway.
- calibas 2y agoHere's a simple example that doesn't use React: https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectE...
- hk1337 2y agoI believe you could probably do most of that with just css now too. Disabling the default pop up from showing up may be the only thing you need javascript to do.
- royal_ts 2y agoI was thinking that it's so weird to talk about using standard HTML validation and then everything is shown with React? If we want to teach people how standard works, we can't assume React as the default.
- everdimension 2y agoI addressed this elsewhere in the comment section, but there's not much "react" going on in the article. I do think that JSX is very expressive and the concern I cover mostly involves the declarative "component" model for writing UIs. It's not react-specific.
- blacksmith_tb 2y agoMy personal bête noire is sites that misuse type=password for 2FA inputs, since that confuses password managers and browsers both.
- teaearlgraycold 2y agoAlso completely unnecessary for passwords that expire in 30 seconds.
- lozenge 2y agoThere is a way to annotate it. autocomplete=one-time-code https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete#one-time-code https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes...
- francislavoie 2y agoTrue, but vast majority of websites don't do the right thing. So password managers need to manage a database of form input overrides. I worked at a small company building a password manager and it was a bit of a nightmare, we had to allocate support staff resources to handling reports of website incompatibilities.
- n_plus_1_acc 2y agoI'm curious, why did you implement your own password manager?
- francislavoie 2y agoI worked for a small company that did. The idea was the password manager lived only on your phone, and you'd connect it to your computer in various ways. Notably including our own hardware, USB nub that connected to the phone app via Bluetooth and acted as a keyboard for the device and the app would instruct it to do the keystrokes to enter your saved credentials. Also a browser extension that the app would connect to over websockets (through our relay servers, DH key exchange to encrypt the connection end to end) and the extension would request the app to send down the credentials on demand. Also we were a very early adopter/implementor of FIDO U2F (security keys). The product kinda hinged on the paranoia of the userbase (which I never aligned with, I trust 1Password and cloud sync'd encrypted vaults for example) so it never really took off. It wasn't "my" product, but I worked on it for a few years, right out of school.
- 1oooqooq 2y agoeverything html offers more exotic than playing text leaves a bad taste in the month thanks to bad implementations. yeah i can mark a field as numeric... but then when a phone renders the number only input all popular keyboards will also leave out every single clipboard buttons and helpers. url where you can also search if you type a phrase? too bad you just lost all typing correcting and prediction. it's lame and hopeless.
- rado 2y agoBizarrely, url validation requires the https:// https:// prefix
- edweis 2y agoThe best native HTML validation is server-side validation. The only downside: the user has to wait 300ms.
- gdwatson 2y agoAnd he loses his page state if there is an error. You have to do server-side validation regardless, but client-side validation can be a lot more pleasant for the user. I used to think it doubled your workload to do both, but if you are using JS-free client-side validation, I think that the server can just return an HTTP error guilt-free for any invalid input that the browser will catch. It’s a pretty good compromise for format validation.
- throw_m239339 2y ago> And he loses his page state if there is an error. No, you can handle that on the server too, easily, since you can fill the form with the last known state upon page loading.
- edweis 2y agoWhen returning an error, you can fill the input values in your HTML response. Indeed the most pleasant UX is to set an additional validation logic on the client side and I don’t think this should the go-to solution.
- account42 2y agoUsing your browser's back navigation from the error page to the form should result in the values still being there unless you are doing something stupid with client-side rendering.
- everdimension 2y agoGreat answer, exactly! Client-side validation isn't meant to remove the need for the server-side checks
- bob1029 2y agoAssuming the actual validation of form input takes ~1ms, this is a fairly unusual amount of latency to experience in 2024. You've got tech stacks and cloud services that will put you within 20ms of 99% of your users. Server side everything is still the safest possible bet you can make.
- ozim 2y agoBecause it sucks. It does not translate with the application but with browsers settings, it doesn’t style or fit any design. It looks differently on different browsers and it is really hard to explain to stakeholders “this is from browser I don’t have control over it”.
- everdimension 2y agoIt does suck, but I think not for the reasons you mention. I truly believe a nicer API would motivate developers to use it, and if native validations satisfy the product requirement, their styling does become a lesser concern. But surely styling is still important, but another great topic to write about is the fact that you actually can opt-in to showing native validity errors in a custom way!
- zelphirkalt 2y agoAnd your application should be looking at ... the browser settings. I could see a case, if a user decides to somehow make a single website use a different language than the others. I guess it would be a browser's job to have specific languages for specific websites.
- ozim 2y agoIt works for presenting or selecting initial language. Even that is debatable because some big players don't even care about that and present language based on location. Explaining to people they should go and change their browser settings is major hassle.
- zelphirkalt 2y agoAutomatic language selection based on location is an anti-pattern. If I am traveling, I don't suddenly switch my brain to another language. Whoever writes websites like that doesn't properly think about it.
- Gormo 2y ago> It does not translate with the application but with browsers settings, it doesn’t style or fit any design Wait, which is it? Does not match any style or design, or is it matching the browser's? And if your application isn't consistent with the browser and OS settings, shouldn't you fix your application?
- DeathArrow 2y ago>Imagine a username input that should be valid only if the username is not taken Maybe that is user friendly but for sure I don't like to see the backend bombarded with API calls each time an user types a letter.
- eru 2y agoIt's not actually all that bad, if you do it asynchronously and in batches (as much as possible). The total amount of traffic in both direction is pretty small, and the logic is simple, especially compared to lots of other things your server is typically doing.
- bugtodiffer 2y agoWebSockets, then it's a couple bytes a click
- mrweasel 2y agoI don't think the amount of traffic is necessarily the issue. You're validation could be fairly "expensive". Maybe you need to do a lookup in a legacy system, maybe you need to check multiple systems? You'd probably have to wait until the user moves on to the next field, if there's more, but that's also a little silly, as you'd force the user to go back to a previous field.
- everdimension 2y agoYou usually create debounced inputs for that. This is similar to the autosuggest and typeahead inputs and comboboxes: sending requests to the server in response to an input change isn't something unusual
- fhdsgbbcaA 2y agoIt’s a major security/privacy issue, you don’t want to tell world+dog all registered users, especially since that’s typically an email address. Huge, huge, massive “no no”. Likewise you still have to do sever side validation as any client side code can be modified, or you can just send payloads directly to the server. IMHO client side form validation is dangerous as it gives a false sense of security.
- JodieBenitez 2y agoDo we finally have a standard solution for input masks ? 25 years ago I was struggling with this while my fellow desktop app devs had good input masks in their widgets, with easy to use pattern syntax. That would be embarrassing if not.
- blueflow 2y agoEvery other website or program now uses a different set of UI patterns. We are not advancing, we are regressing. I do miss when textboxes had inset and buttons had outset borders.
- account42 2y agoThe last example is bad. You shouldn't scream at your users before they even had a chance to enter the required information so the second password field should not be marked red until the user either is done entering text there (onblur) or tries to submit the form.
- a2128 2y agoThis is one of my big gripes - when apps are trying to get ahead of me with validation or submission. When I'm entering a 2fa code, I don't need a big red error telling me that the code must be 5 digits before I'm even finished. Worse is when they immediately auto-submit upon entering the last digit, so if I made a mistake I can't backspace and correct it
- everdimension 2y agoThat's totally true! Invalid states shouldn't be shown sooner than necessary It's just that for the demos in the article it makes sense to show invalid states as soon as possible, but for a nicer UX in real apps you need to take into account "touched" and "submitted" states for the form and per input For the demos I wanted the reader to know at a glance when our validation code takes effect and this obviously comes at a conflict with demoing a fully "real-world" behavior
- k__ 2y agoBuilt-in validation is pretty much the only reason I use forms. Capturing input with frameworks is much simpler than pulling the values out of an event object, so I'd be okay with just using input and button elements. Yet, that doesn't trigger the validation, so I end up wrapping it with a form element and using a submit button.
- lelanthran 2y ago> Yet, that doesn't trigger the validation, so I end up wrapping it with a form element and using a submit button. I run the validation manually using `reportValidity()` on `element.querySelector(...)` before passing it on to whatever.
- yakshaving_jgt 2y ago> Using other input attributes that create constraints, such as "pattern" or "maxlength" No. Don't use the maxlength attribute. https://adamsilver.io/blog/dont-use-the-maxlength-attribute-to-stop-users-from-exceeding-the-limit/ https://adamsilver.io/blog/dont-use-the-maxlength-attribute-...
- everdimension 2y agoThat's great advice! I also dislike the "character rejection" mechanisms, even though many people love it and products often ask to implement it. To add to the possible solutions mentioned in your article, I'd add the "pattern" attribute. You can do something like this: <input pattern=".{0,6}" /> This will allow input of any length, but show a warning then the value is longer than six characters.
- jrochkind1 2y agoi'm not seeing the custom validation messages in these examples at all in Chrome. Others are?
- everdimension 2y agoThat's weird! Have you tried submitting the forms in the examples? The custom messages are supposed to be shown in the native browser validation tooltips. The support for those is quite good! Even on mobile browsers
- jrochkind1 2y agoYup. If it's just me, I guess it's some plugin I have installed or something.
- Vox_Leone 2y agoGuilty. Recently, when I was involved in a project that required a lot of attention to forms, I ended up overlooking the importance of basic simplicity. I regret it a bit. Thanks for sharing your perspective.
- kaoD 2y agoMy product just failed an accessibility audit because we are using native HTML form validation and the official recommendation was to implement our own validation layer. EDIT: which I agree with. Native HTML validation has many flaws and visual customization is not my biggest concern to be honest (but it's the nail in the coffin). E.g.: - It's impossible to show multiple errors at once per field unless you concat strings ("You need a number. You need a symbol. Must be >10 chars.") This is both bad UX and bad for accessibility (you cannot navigate concatenated strings on the accessibility tree). And this isn't even implementation dependent, it's the spec! You need multiple errors at once because playing whack-a-validation-error is not fun for users. - It's browser-dependent which is bad because you can't control it and because the implementation is generally terrible (e.g. in Chrome it shows a popup on focus, which is not very accessible by itself because (1) it's a popup (2) that shows modally (3) and can't show all form errors at once). Not using popups for important information is accessibility 101, but browsers cannot afford to do anything else without interfering with the actual document. - You still need custom validation for form-wide errors (like errors that don't belong to a particular field, "Fields A and B are incompatible") so you might as well have a consistent validation story. - It requires you to have hidden inputs to be consistent (-ish) if you have some custom input that doesn't fit any of the native input types -- this breaks accessibility too and fixing it is as hard as having your own accessibility-friendly validation story. - The custom validity API is imperative and cumbersome to use. Not using custom validity is almost never an option unless you want terrible messages ("This field is invalid") And many more. HTML form validation is terrible.
- josephcsible 2y agoWhat was the auditors' reasoning for that?
- kaoD 2y agoThat the browser implementations are generally terrible and wouldn't pass accessibility audits, so all browsers would have to change and then some time to pass for the fixed versions to be widespread. We didn't discuss browser-specific issues in detail, but I edited some points in my original message that highlight some of the issues that I suspect make it a no-go for accessibility.
- acdha 2y agoI share the wish that there was more effort in the browser space to improve the built-in controls but I would also recommend that people thinking they can easily do better try some real usability and especially accessibility testing. One very nice trait of the standard APIs are that they’re very lightweight and people who build assistive tools like screen readers and Braille displays know about and support them. It is so easy for developers to think they have something better after a simple NPM install, until they test it on a slow (i.e. median) phone or watch a blind person try to use their application and then spend weeks trying to improve things. Given how common web forms are it’d be really nice if we had an Interop-style competition focused on making the out of the box experience better for normal people both for the controls integrated in browsers and the myriad of JavaScript widgets.
- deleted 2y ago[deleted]
- vips7L 2y agoIn React I just use Formik and Yup to make forms painless. I've yet to discover a better way.
- gtsop 2y agoAre we seriously talking of HTML by using React examples? The article doesn't even explicitly aknowledge the fact that it is written within the context of react.
- burnte 2y agoA lot of HTML features are underused with everything being done in JS libraries now rather than using built in functions.
- CRConrad 2y agoOne gets the feeling HTML in general is underused, since everything has been done in JavaScript for... How long now, at least over a decade? It's gone so far that some peole claim React (and probably other frameworks too) is "a language"; they apparently don't even know it's just a JavaScript library.