DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Automating the Migration From JS to TS for the ZK Framework
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • Why React Router 7 Is a Game-Changer for React Developers
  • Storybook: A Developer’s Secret Weapon

Trending

  • Web Crawling for RAG With Crawl4AI
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  1. DZone
  2. Coding
  3. JavaScript
  4. Enhance User Experience With a Formatted Credit Card Input Field

Enhance User Experience With a Formatted Credit Card Input Field

This article shows how to implement a credit card input that automatically formats numbers into readable four-digit groups in Java and JS for an enhanced user experience.

By 
Hawk Chen user avatar
Hawk Chen
DZone Core CORE ·
Updated by 
jean yen user avatar
jean yen
·
Oct. 29, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
6.4K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, I will guide you on how to create a credit card input by extending existing ZK components. Moreover, I'll apply a customized ZK JavaScript widget to format the card numbers in groups of four digits, improving readability and user experience. Additionally, we'll integrate a custom JavaScript widget to ensure that only numeric input is accepted.

This guide is ideal for web developers needing a dedicated input field for credit card information. Using the ZK UI Framework as an example, I’ll walk you through creating a well-structured, readable credit card input box.

Start With One Textbox

The ZK framework provides ready-to-use UI components including input controls, so the most straightforward approach is to use a single Textbox in a Zul page to accept a credit card number. It's as simple as:

XML
 
<textbox type="tel" cols="16" maxlength="16"/>


  • maxlength="16" ensures that users cannot enter more than 16 digits.
  • cols="16" sets the textbox width to fit approximately 16 characters, ensuring the field visually matches the expected input length.

 The result looks like this:
Credit card number showing numbers crowded togetherHowever, the downside is that all the numbers appear "crowded together," which makes them difficult to read.

Creating a Number Padding Box

To make the input more user-friendly, I can improve its readability by customizing the textbox to format the digits in groups of 4 digits. This is commonly seen in online payment forms where credit card numbers are displayed as 1234 5678 1234 5678. 

I start by analyzing how the framework and the default textbox work. Each ZK component has 2 entities:

Analyzation showing how the framework and the default textbox work

  • Java object: Allows you to control a UI component with Java API
  • JavaScript widget: Determines the client-side behavior

To group the numbers, I need to add custom behavior to the textbox by extending its JavaScript widget. The widget will automatically insert a space after every four digits as the user types and will remove any non-numeric characters.

Credit card box showing numbers spaced after every four digits

Here's the logic and where you would need to insert it in TypeScript:

TypeScript
 
@zk.WrapClass('business.input.NumberPaddingBox')
// @ts-ignore
class NumberPaddingBox extends zul.inp.Textbox {
    /** default onInput event listener **/
    doInput_(event: zk.Event) {
        super.doInput_(event);
        this.removeNonNumericCharacters();
        this.addPaddingEach4Digits();
    }

    removeNonNumericCharacters() {
        // @ts-ignore
        this.getInputNode().value = this.getInputNode().value.replace(/\D/g, '');
    }

    addPaddingEach4Digits() {
        // @ts-ignore
        let value = this.getInputNode().value;
        // avoid exceeding credit card number length when pasting texts
        value = value.substring(0, 16);
        // @ts-ignore
        this.getInputNode().value = value.replace(/(\d{4})(?=\d)/g, '$1 ');
    }

    getZclass() {
        return 'z-textbox';
    }
}


  • removeNonNumericCharacters(): Enforce to allow number characters only.
  • doInput_(): ZK widgets provide a function naming convention to register an event listener: do[EVENT_NAME]_() is the default handler for the event on[EVENT_NAME]

Apply Custom JavaScript Widget

Now that we have the formatting logic, it is simple to apply this customized JavaScript widget to a textbox:

XML
 
<zk xmlns:w="client">
    <textbox type="tel" cols="19" maxlength="19"  w:use="business.input.NumberPaddingBox"/>
</zk>


  • By default, a tag attribute indicates a Java component's attribute. In this case, I want to specify an attribute for the JavaScript widget, so I have to use XML namespace.

Declare It as a ZK Component

This would apply the custom JavaScript widget to a specific <textbox>. For ease of use, it's beneficial to declare this setup as a ZK component. This way, developers can use it like a regular component without specifying a custom widget name. Additionally, you can set default attributes for the credit card input.

An example declaration in lang-addon.xml:

XML
 
<language-addon>
    <addon-name>business-input</addon-name>
    <depends>zul</depends>
    <language-name>xul/html</language-name>
    <version>
        <zk-version>10.0.0</zk-version>
    </version>
    ...
    <component>
        <component-name>creditcardbox</component-name>
        <extends>textbox</extends>
        <widget-class>business.input.NumberPaddingBox</widget-class>
        <property>
            <property-name>type</property-name>
            <property-value>tel</property-value>
        </property>
        <property>
            <property-name>cols</property-name>
            <property-value>19</property-value>
        </property>
        <property>
            <property-name>maxlength</property-name>
            <property-value>19</property-value>
        </property>
    </component>


  • <widget-class> declares the custom JavaScript widget.

Check lang-addon.xml specification.

After adding this declaration, I can use it as a normal component in a zul like this:

XML
 
<creditcardbox/>


Give It a Try

I’ve shown how small adjustments can significantly enhance the user experience of your web app. To give it a try, simply clone this ZK project from GitHub. Then, include the artifact in ZK Maven repository, specify <creditcardbox/> in a zul, follow the readme to start the server, and visit the zul with your browser.

JavaScript UI User experience Java (programming language) ZK (framework)

Opinions expressed by DZone contributors are their own.

Related

  • Automating the Migration From JS to TS for the ZK Framework
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • Why React Router 7 Is a Game-Changer for React Developers
  • Storybook: A Developer’s Secret Weapon

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!