13 ms·
Cleave.js – Format input text content when you are typing
- dceddia 8y agoThe credit card one is cool, but when I clicked it and Chrome offered to autofill my credit card, the first thing that popped into my head was "hmm, this would be a sneaky way to siphon some credit card numbers." Paranoid? Maybe. It made me ponder how I seem to be growing more suspicious of things on the modern web though.
- kamikaz1k 8y agoCan you elaborate on how you expect them to siphon Credit Card numbers? Are you speaking of the demo, or are you saying of potential users of the library?
- folkhack 8y agoChrome offered to auto-fill his CC number that is stored with his expiry, name on card, and (maybe) payment address/zip... everything but the CVV, (card verification number, usually three digits). Chrome is pretty clever these days with payment details and tries to help you keep a "wallet" so-to-speak which acts like an "autofill" feature. Do some searches around Web Payments, Payment Request API, W3C Payment Request, blah blah - let's just say it goes a lot deeper than basic autofill =) Now for siphoning. That attack (as far as I know) wouldn't be allowed to happen. Chrome WILL NOT autofill your details or inject ANYTHING into the DOM until you've entered/verified your CVV. Due to security with how payments work there has to be some sort of a user interaction before any PAN is allowed to populate the DOM. This is to avoid his exact paranoia where a CC num gets entered automatically w/o a user's knowledge. Since this is enforced by the browser I consider it to be pretty safe, and appreciate the feature in my day-to-day browsing activities =) Back to the Cleave.js lib though - that thing is going to BARF on things like CC num autofill driven by browsers/etc. Trying to be super clever is just going to screw-up native browser capabilities.
- deleted 8y ago[deleted]
- wsgeorge 8y agoI had a similar thought when trying the phone number field. I immediately thought "hey, this is what I've been keeping away from Yahoo for years..."
- sam_goody 8y agoOf course, if you were just a tad _more_ paranoid you might not be so thrilled that Chrome is storing your credit card details, your address and the passwords to every sites you trust it with in a way that is accessible to Google. They are not just storing a hash, as that would prevent them from offering the data back to you to fill in passwords et al. And they are not just storing it locally * , I assume that is for your benefit as well, maybe if you switch computers? * This I know from a popup on Vivaldi, which never informed me it is sending my passwords to Google for "safe"keeping, until I tried to change a password and it told me I need to login to my Google account....
- jsf01 8y agoThis is a weird API for what it’s trying to achieve. Why make every Cleave instance use a boolean to determine its type + some related other field that varies based on which type happens to be set to true? Doing it this way prevents tree shaking from getting rid of all the methods you’re not using. If instead it was something like: cleave.Date(...), cleave.Phone(...), etc. then each of those constructors could implement specific options that are relevant. As it is now, you could have an onCreditCardTypeChanged() method on a date input. And if you did it in a manner like I’m proposing, you’d be able to import just the specific formatters you need, allowing your module bundler to strip out the rest.
- rounce 8y agoGlad I'm not the only one that thought the API was a bit 'interesting'. I was also wondering what happens when you set `phone`, `date` and `creditCard` to `true` in the same config and pass it to the constructor? Surely this should at least be a single field, if not separate classes/prototype chains (as jsf01 mentioned).
- franze 8y agoNever write the form lables into the form fields. Chrome Form Autofill is a common use case for all forms. And you can not QA if everything was put in correctly if the lables are part of the form.
- nmstoker 8y agoIf they can fix the backspacing issue on Android this will be superb for things like UK sort codes (NN-NN-NN) which invariably are handled badly for mobile users (eg the most common case being the switching to alphabet from numeric keyboard with each pair of digits being in a distinct box)
- teknopaul 8y agoI dont understand this. For sort codes why not just type six digits? What do you get from inserting the dashes?
- miohtama 8y agoThis is a half way solution, as you can see a lot of artifacts like when typing numbers to the time field when it is already full. The only way to properly address this is to bring this as native HTML5 components. Then different UX paradigms, like desktop and mobile, can properly handle complex input. This shows the shortcoming of web UI. You cannot properly address shortcomings of browsers on low enough layer. It is not an issue for native apps.
- yawaramin 8y agoI wonder if it might be used for something like formatting plaintext Git commit messages. Rules would be things like 'subject line 50 characters, then blank line, then paragraphs or bullet points of 72 characters'. That would solve a major issue with writing commit messages on the web.
- IgorPartola 8y agoI am seeing a lot of criticism of this library in the comments. Does anyone have better suggestions aside from “just let the user enter ‘fuck you’ for a date and ‘screw this’ for their phone number”? I am currently using Cleave for a project where the customer unequivocally requested this kind of functionality. Specifically I need to implement phone masking, date masking (no calendar pickers except native mobile ones allowed), and number and currency validation and masking. Cleave was the least opinionated library of its kind that I found.
- morpheuskafka 8y agoI don't have direct experience but libphonenumber looks pretty comprehensive: https://github.com/googlei18n/libphonenumber https://github.com/googlei18n/libphonenumber
- mgbmtl 8y agoyep, it's what Cleave.js uses for phone number formatting.
- tcd 8y agoNo JS library will stop that when you can just POST the form directly. Best let the user input as they please and let the server do the rest.
- tokyodude 8y agoI would prefer a generic <input type="text"> or <input="number">. Choose the one that gives me the best input experience on mobile. <input="email"> if it's email for example. I would then prefer some live validation JavaScript that highlights if my input is wrong and tells me what it think is wrong but does not mess with my input. Ideally the JavaScript validation does not warn me in until I leave the field because if say I'm typing a phone number and after 1 digit the field turns red, to me that feels like shouting "Hey IDIOT! ONE DIGIT IS NOT A PHONE NUMBER!" which of course I know I just hadn't finished typing. On top of that I want the form to not be stupid. Let me enter 555-555-5555 or 5555555555 for a phone number. Let me enter 1111222233334444 or 1111 2222 3333 4444 for a CC number. Let me enter 01/19 or 1/19 for an expiration date. Trim whitespace on submission too. Don't force me to jump through hoops the code should be smart enough to deal with. Don't correct this kind of text in the field, correct it on submission. If something is ambiguous then add that to your validation message.
- morpheuskafka 8y agoPerhaps they should read this: https://news.ycombinator.com/item?id=19214035 https://news.ycombinator.com/item?id=19214035 Phone numbers are something you dial into a phone. They are not a alphabetic ISO code and then some numbers. Country codes and international dialing codes are NOT 1:1. North Korea for example has two dialing codes but is one county. Many island nations share the US's +1. Staphones have their own dialing prefixes that don't correspond to an ISO country code. With all due respect, this code is a disaster and it is guaranteed to lead to problems when one of these many edge cases is hit.
- tokyodude 8y agoWow, horrible! I tried to select a few characters and copy and paste but it didn't copy the part I selected. instead it copied everything. Also if you tell me the format is 00:00:00 then I'm going to type digit digit colon digit digit colon digit digit but instead you auto inserted the colon which means now my typing and correcting muscle memory is doesn't match. I typed 8 characters so it should take 8 key presses to backspace or 8 characters to go left. Please don't use these on your site
- dmix 8y agoStrange how Visa starts with 40-49 (10x) while Mastercard is only 51-55 (4x). I wonder if there is any logic with these prefix numbers.
- jmiserez 8y agohttps://en.wikipedia.org/wiki/Payment_card_number https://en.wikipedia.org/wiki/Payment_card_number >The first (leading) digit of the IIN identifies the major industry of the card issuer. 4 and 5 stand for "Banking and financial". >The leading six digits of the card number is the issuer identification number (IIN), sometimes referred to as the "bank identification number (BIN)". There's a list of all 1000000 possible IINs/BINs, but it's not publicly available: >The official "ISO Register of Issuer Identification Numbers", is not available to the general public. It is only available to institutions who hold IINs published in the Register, financial networks and processors. Institutions are required to sign a licensing agreement before they are given access to the Register. Several IINs are well known, especially those representing credit card issuers. It's a bit like IP address blocks: there's is/was some logic to it, but to actually know which bank a IIN/BIN belongs to (after mergers, acquisitions etc) you have to look it up in the register.
- dmix 8y agoThanks this answers exactly what I was looking for. One of those things you have in the back of your mind that you want to look into one day.
- sriram_malhar 8y agoThis is very nicely done. Personally I prefer my data entry to be a simple text field so that I can use backspace, or clipboard paste, or insert/delete from the middle normally. Meanwhile, the UI can show its interpretation of what I entered just above the field. For example, if I enter a date field 2/25, the software could show its interpretation (02/25/2019) as I type, allowing me to quit typing as soon as the interpretation is correct. Likewise with credit cards: it isn't a big problem hitting a space bar to separate, but that's my choice. In other words, the beautiful formatting is good, but keep the input field and the eventual rendering of the field separate.
- ulucs 8y agoFollowing the comments posted here, I think the proper way to format input is to split the transformations into two. The credit card example gives us purely cosmetic changes and it makes sense to apply them in real-time so the user receives important feedback. The other type is the application of strict formatting, like in the date format example. It's really nice to infer 1992223 as 1992/02/23, but it robs some control from the user. As we're already inferring what the user is trying to say, we could show them 1992/2/23 to give them feedback and apply the transformation before sending the data, thus having the best of both worlds.
- kuon 8y agoJust don't, I want simple text fields where I can type without being attacked by a script. I want my autofill to work properly, I want to be able to copy paste without any strange behaviour. I want to type the delimiter. And you should be locale aware, for 2019-02-24 I would type 24.2.19. Of course you might target only the US market with your form, but the problem is that bad practices are spreading to global developers.
- happppy 8y agothis is super great
- surfsvammel 8y agoI like it. Never do any front-end stuff, but if I ever do I’ll look it up.
- jacknews 8y agoI'm sorry to say this is everything I hate about "modern" UI. It looks fantastic, but, for example, the YYYY/MM/DD field, I can't just write 19/2/23 or whatever (explicitly entering the delimiting slashes), I have to follow the prescribed format, 2019/02/23 (oh, ok thankfully 2 gets filled to 02 automatically). Try 1/20 in the MM/YY field. Doesn't work. It seems fairly simple to fix; when the user types a delimeter, trust them.
- deleted 8y ago[deleted]
- thegeomaster 8y agoYep, I encountered the same issue and became frustrated within seconds. From a user's perspective: I'm trying to enter a character which makes perfect sense in context, but the key press is ignored. There's no reason to restrict the user's actions in such a way.
- leeoniya 8y ago> Try 1/20 in the MM/YY field. Doesn't work. i've never seen a card that specified expiration month with a single digit. google images for "card expiration" does not bring up any examples either. a placeholder="MM/YY" should make it clear that both are needed.
- teknopaul 8y agoFYI Firefox mobile was unable to enter dates in January. I agree this is bad practice. I have similar code in an app I'm writing right now, I also didn't consider the usability issues or wierd delete cases. Gonna remove the code after reading this thread. Falls under trying to be clever. I think slightly increasing the space between groups of numbers might be acceptable? Anything that magically inserts characters seems to be problematic.
- jeroenhd 8y agoTo humans, 01 is the same as 1. To computers, there's two integers separated by a slash. While it's true that there's a leading 0 on the card itself, there's no reason not to just split on the / and convert both sides to integers.
- iambateman 8y agoThis looks great! I typically use an individual library to format. One request I didn’t see: money formatting.
- Klathmon 8y ago>One request I didn’t see: money formatting. Probably for a good reason. Formatting currency should be handled by the i18n system, because that's what it is. Take one thousand dollars in US currency, it can be displayed as: $1,000.00 $10,00.00 $1.000,00 $1,000.00 USD 1,000.00 $ $ 1 000,00 and more. And that's not even counting negative numbers which can change their display format based on the industry it's used in, let alone the language. Then add in other currencies in different locales, often the currency symbol is after the currency, some locales use different spacing, some don't have a decimal to their currency in common usage, some use the same symbol for different currencies ($ could mean USD or CAD or more and in some cases that can be a big mistake) and a LOT more edge cases.
- moolcool 8y agoPrefix is broken-- put the cursor before the 'P' in the example and press any letter 6 times
- tlb 8y agoWhen I’m just trying to get past a signup form, please don’t make me re-learn a new way to type. Here, the delete key does something other than delete the last keypress. For example, typing 20199<delete>11 gets me 2019/01/1 because it helpfully autoinserted the 0 before the 9 and didn’t undo it. Filling in a form is never delightful. It’s a tedious interruption in my flow. Just let me get past it with minimum cognitive load.
- iamgopal 8y agoA much simpler approach is to show in realtime what computer will interpret of current input without changing the input, instant feedback is a much more better approach to improve quality of input.
- hartator 8y agoDo you have an example of good integration of this? Interesting.
- julienreszka 8y agohttps://www.lukew.com/resources/web_form_design.asp https://www.lukew.com/resources/web_form_design.asp
- allover 8y agoThis sounds like a cool idea, like sibling I'd also love to see a good example of this :)
- g105b 8y agoI found this library many moons ago when looking for a credit card formatting solution. It had so many bugs when I tried it, and it has at least as many now. For example: in the first demo, type the card number 1234567812345678. Works nice, eh? Now try again with 1233567... oh wait, let me go back and change that second "3" to a "4". And it's broken.
- tomp 8y ago
- calebclark 8y agoIt's a good library -- I've used it multiple times. However, I'm curious why its trending at the top of Hacker News. It's been around since 2016.
- petercooper 8y agoMight be a coincidence but we included it in this week's JavaScript Weekly on Friday: https://javascriptweekly.com/issues/425 https://javascriptweekly.com/issues/425 .. we probably saw it come up somewhere else though. One of those organic things.
- jwr 8y agoI hate this idea. Why does every credit form out there have to invent new ways to "format" credit card numbers and do fancy stuff behind my back? I have to learn how every form works, because cursor keys, delete, and punctuation no longer behave like everywhere else. Invest all the effort into reliable, flexible and intelligent parsing of whatever the user types in. Even in 2019 I find web forms (banks excel at this) which complain about "invalid" characters instead of ignoring them. Incidentally, this idea of "let's improve the standard user interface to make it easier for ORDINARY PEOPLE" is not limited to web forms. Browser URL fields are a playground for programmer creativity and I'm regularly baffled by their behavior: autoselecting the entire input, suggestions completing what I typed even though I never asked for it, and similar ideas.
- rhizome 8y agoBlow into your device's left microphone to use VISA. Blow into the right one for American Express.
- tardismechanic 8y agoUgh! Please don’t give them new ideas!
- humanbeinc 8y agoI type in my phone number in and THEN select the country..my number gets deleted... I hate you now
- acdha 8y agoI just noticed the same bug. It’d be a little more tolerable if it auto detected that e.g. +1 meant US or suggested based on the browser locale rather than requiring you to scroll a huge list but deleting input is almost always a mistake.
- folkhack 8y agoI've tried similar libraries and they all suffer the same general "I don't know what the backspace key just did" sorta issues... Just look at the top features listed on their Github: * CC number - doesn't actually support all PAN formats - 19 digits exist although extraordinary rare. NEVER try to do anything fancy with your CC details field because if people try to pay you and can't you've lost a customer. * Phone number formatting - doesn't support all phone # formats. Leave this as flat text (non-numeric) or numeric for base telephone # and a text field for extension. * Date formatting - use type="date" so you get native mobile support for date entry. * Numeral formatting - use type="number" so you get native mobile support for numeric entry.
- pmarreck 8y agoYour response is assholish. Try being more compassionate next time, some dude probably worked on this on his own time, and these issues you’ve noted can be fixed.
- folkhack 8y agoSure but look at the top-level comments on here and there are words like: * "anti-pattern" * "overzealous autocorrect" * "this is everything I hate about 'modern' UI" * "I hate this idea" * "This is a weird API for what it’s trying to achieve" * "...THEN select the country..my number gets deleted... I hate you now" * "Cute, but it looks like it's trying too hard to be clever." * "Couldn't find my country for the phone number (UK). Looked for EN and UK, eventually discovered it was GB. Hard!" * "hot garbage trash" - wait whoops ... that's mine - seems to fit right in though! It actually took me a few consecutive quotes before I even found a neutral sounding "should simply be solved by browsers imho" comment. "Your response is assholish" is correct, and I will agree. However I have a visceral reaction against these anti-patterns. The web is suppose to be open, and the web is suppose to be usable by a diverse group of people (including those with disabilities). I don't care if someone built this in their "free-time", this is NOT a responsible front-end lib to use.
- rob 8y ago
- ken 8y agoCute, but it looks like it's trying too hard to be clever. Are you expecting websites to show a giant pop-up menu of 2-letter country codes to users? Or are you expecting websites to hardcode one country, and reject phone numbers which don't match that pattern? And what about extensions? For dates, most browsers support form type="date" and the like. That's going to be better than whatever you use here. For credit cards, it's fine, because 16 decimal digits is a universal standard. For anything else, it's going to cause as many problems as it solves.
- leesalminen 8y agoAmerican Express cards are 15 digits.
- ken 8y agoHa! Shows what I know. Exceptions abound.
- jarekkruk 8y agoFor phone numbers if you accept numbers without country code then you need to know it. This library correctly handles numbers with country code without specifying the country in other way.
- hit8run 8y agoNice lib. Though many of these things should simply be solved by browsers imho. As developer I simply want to render input with the type of phone and be good. Let those who provide the operating system/browser handle the details in a standard way.
- aboutruby 8y agoFor credit card and bank accounts, Stripe Elements has some battle-tested React inputs: https://stripe.dev/elements-examples/ https://stripe.dev/elements-examples/
- deleted 8y ago[deleted]
- systematical 8y agoWe implemented this recently because a design that was dropped on my desk called for it, cause you know, marketing people. I was pretty happy with the library, but after reading some of the reviews on here I think we are going to have to look into how it plays on some devices and use-cases again.
- hathawsh 8y agoMy Google-foo is failing me: isn't there a site that catalogs UX/UI anti-patterns? This library edits what the user types in real time, which is a serious anti-pattern because it causes users to compound mistakes. I would call it the "overzealous autocorrect" antipattern. For example, if I want to type in the date "2017-03-30", but I accidentally type "2017-02-30", this library silently changes the day in addition to the month, leaving me with "2017-02-28". I suppose you could use this to illustrate how fallible humans are, but if your goal is to minimize errors, you simply can't autocorrect number fields. You must show error messages.
- hnacc0 8y ago>isn't there a site that catalogs UX/UI anti-patterns link
- mch82 8y ago“Input Masking” is a UX design pattern. The implementation of the date field mask could be better.
- pault 8y agoI have to deal with exactly this issue at work on a project that emulates spreadsheet behavior for number formatting. I learned immediately that you have to format on blur, because anything you do to the input value while the user is typing will move their cursor to the end of the input, and no amount of clever prediction will put it back in the right place in all cases. Always format on blur unless you want your users to hate your app.
- Zarel 8y agoYou can detect where the cursor is before editing the input value, and place it in the correct place afterwards. This is a pretty basic trick used in many different places, including by Cleave itself.
- pault 8y agoI think my comment has been validated by the dozens of comments here complaining about broken inputs. I didn't say it was impossible; the basic trick only works in simple cases and the edge cases are numerous. If I implement a feature and it causes even one person to bounce, it's a failure.
- jrh206 8y agoCouldn't find my country for the phone number (UK). Looked for EN and UK, eventually discovered it was GB. Hard!
- 2T1Qka0rEiPr 8y agohttps://en.wikipedia.org/wiki/ISO_3166-2:GB https://en.wikipedia.org/wiki/ISO_3166-2:GB - we failed :D
- GordonS 8y agoSo, as a developer I know my country's 2-digit ISO code, and those of plenty of other countries - the point is, the general population doesn't.
- jrh206 8y agoQuite!
- 2T1Qka0rEiPr 8y agoHeh, no I wasn't assuming that you didn't know, I guess I was just pointing out that our ISO code is silly!