Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • Asp.net Core
    • C
    • C#
    • DotNet
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. JavaScript
  4. Decimal validation in JavaScript

Decimal validation in JavaScript

Date- Aug 14,2022

Updated Jan 2026

5823

Understanding Decimal Validation

Decimal validation is the process of ensuring that user inputs in a text field conform to the expected format of decimal numbers. This is particularly important in applications where precision is crucial, such as banking, e-commerce, and scientific applications. By enforcing decimal validation, we can prevent errors related to invalid data entry and improve the overall user experience.

In JavaScript, there are multiple ways to validate decimal inputs. One common method is to use event listeners that trigger validation functions when a user types in an input field. This allows for real-time feedback and helps users correct their input immediately.

Implementing Decimal Validation Using onkeypress Event

To implement decimal validation, we can use the onkeypress event of an input box. This event captures keyboard input before it is entered into the text field. Below is an example of how to set up an HTML form that only accepts decimal numbers:

<form>
    <div class="form-group row">
        <label for="inputNumberWithDecimal" class="col-sm-2 col-form-label">Enter Only Number And Decimal</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputNumberWithDecimal" placeholder="Enter Only Number And Decimal" value="" name="inputNumberWithDecimal" onkeypress="return onlyNumberWithDecimal(event)" />
        </div>
    </div>
</form>

In this example, we create a simple form with an input field. The onkeypress attribute calls a JavaScript function named onlyNumberWithDecimal.

JavaScript Function for Validation

The validation function checks if the input character is a digit or a decimal point. Here is the code for the onlyNumberWithDecimal function:

function onlyNumberWithDecimal(evt) {
    try {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        // Allow digits and decimal point
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
        return true;
    } catch (err) {
        alert(err.Description);
    }
}

This function uses the evt.which and evt.keyCode properties to determine the character code of the pressed key. It allows the decimal point (code 46) and digits (codes 48-57) while blocking other characters.

Enhancements for Improved User Experience

While the basic implementation works, there are several enhancements we can make to improve user experience. For instance, we can allow users to paste valid decimal values into the input field. To achieve this, we can add an oninput event listener that validates the entire input value.

<input type="text" class="form-control" id="inputNumberWithDecimal" placeholder="Enter Only Number And Decimal" value="" name="inputNumberWithDecimal" onkeypress="return onlyNumberWithDecimal(event)" oninput="validateDecimalInput(this)" />

Here’s how the validateDecimalInput function can be implemented:

function validateDecimalInput(input) {
    const regex = /^\d*\.?\d*$/;
    if (!regex.test(input.value)) {
        input.value = input.value.slice(0, -1);
    }
}

This function checks the entire input against a regular expression that matches valid decimal numbers. If the input does not match, it removes the last character.

Edge Cases & Gotchas

When implementing decimal validation, it's important to consider edge cases. For example, how should the application handle multiple decimal points? Our current implementation will allow multiple decimal points, which is not valid. We can modify the onlyNumberWithDecimal function to restrict this:

function onlyNumberWithDecimal(evt) {
    var input = evt.target.value;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    // Allow only one decimal point
    if (charCode == 46 && input.indexOf('.') !== -1) return false;
    // Allow digits and decimal point
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
}

Another edge case to consider is when users enter a negative sign. Depending on the application requirements, you may want to allow negative decimals. If so, you would adjust the validation to permit the negative sign at the beginning of the input.

Performance & Best Practices

When implementing input validation, it's important to maintain performance, especially for applications with many input fields or complex forms. Here are some best practices to follow:

  • Debounce Input Validation: If you're validating on every keystroke, consider debouncing the validation function to reduce the number of calls.
  • Use Regular Expressions: Regular expressions can be a powerful tool for validating input formats. Ensure that your regex patterns are optimized for performance.
  • Provide User Feedback: Consider providing visual feedback for invalid inputs, such as changing the input border color or displaying an error message.
  • Accessibility Considerations: Ensure that your validation messages are accessible to screen readers and that users can navigate the form easily.

Conclusion

In this blog post, we explored how to implement decimal validation in JavaScript, ensuring that users can only enter valid decimal numbers in text fields. We covered the basics of using the onkeypress event, enhancing user experience with input validation, and addressing edge cases that may arise.

Key Takeaways:

  • Decimal validation is essential for ensuring data integrity in numerical inputs.
  • Using JavaScript event listeners allows for real-time validation of user input.
  • Enhancements can improve user experience, such as allowing paste functionality and providing immediate feedback.
  • Consider edge cases and performance best practices when implementing validation.

S
Shubham Batra
Programming author at Code2Night β€” sharing tutorials on ASP.NET, C#, and more.
View all posts β†’

Related Articles

Input validations using javascript
Aug 14, 2022
Previous in JavaScript
Alphanumeric validation in JavaScript
Next in JavaScript
Input validations using javascript

Comments

Contents

🎯

Interview Prep

Ace your JavaScript interview with curated Q&As for all levels.

View JavaScript Interview Q&As

More in JavaScript

  • Complete Guide to Slick Slider in JavaScript with Examples 14834 views
  • Card Number Formatting using jquery 11557 views
  • Alphanumeric validation in JavaScript 8776 views
  • Jquery Autocomplete 8389 views
  • Input Mask in Jquery 7459 views
View all JavaScript posts β†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • Asp.net Core
  • C
  • C#
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  Β·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor