Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. JavaScript
  4. Decimal validation in JavaScript

Decimal validation in JavaScript

Date- Aug 14,2022 Updated Jan 2026 5878

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
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

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 14952 views
  • Card Number Formatting using jquery 11626 views
  • Alphanumeric validation in JavaScript 8836 views
  • Jquery Autocomplete 8445 views
  • Input Mask in Jquery 7544 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 | 1770
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
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • 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