Advertisement
Tech

Validating Input at the Client: check numeric value fields

Input fields that are expected to collect only numeric values can be validated at the client’s browser

By Carmelo Carbonara
Desk Tech
Reading time 2 min read
Word count 310
Web development Internet HTML articles
Validating Input at the Client: check numeric value fields
Advertisement
Quick Take

Input fields that are expected to collect only numeric values can be validated at the client’s browser

On this page

Introduction

The code view below uses a text input tag and we’re expecting a non-negative integer for the quantity value. The div tag is a space where we can write a message if necessary.

Checking for numeric values may require a series of tests and steps:

Advertisement
  • first trim the value
  • if it’s not at all numeric stop and alert the user
  • if it is numeric, is it a non-negative number; otherwise alert the user
  • if we require integers, round the value

Code view for Checking Numeric Values

This example applies the function chkField(whichObj) to the onblur event of the input field. The function chkField(whichObj) passes execution to testNumeric(whichObj) and expects a return value of true or false - if false, stop and ask the user for valid input. This could be applied as an onsubmit event if the quantity input field were part of a form. If the value entered for quantity is anything other than a positive integer it stops and alerts the user to enter a valid quantity.

Code view

Advertisement

Quantity 

Conclusion

Checking for numeric values involves a few steps. We could require validation within a range or as an appropriate date string. We may also want to check for blank fields and trim leading and trailing spaces and linefeeds.

Advertisement

This post is part of the series: Web Design using DHTML and the DOM

Creating web sites with DHTML based on the DOM can increase server performance, lower bandiwdth utilization and solve most cross-browser compatibility issues.

  1. Getting Elements Using the HTML DOM and JavaScript
  2. Applying Events to DHTML Web Pages Using Javascript and the DOM
  3. Validating Input at the Client: Check for blank or required fields
  4. Validating Input at the Client: trim the field
  5. Validating Input at the Client: check numeric value fields
  6. Leveraging CSS Styles
  7. DOM getElementsByTagName Method for Bulk Element Formating
  8. Unraveling the JavaScript Switch Statement
Keep Exploring

More from Tech

Filed under
Web development Internet
More topics
HTML articles
Advertisement