Textbox
Numbers
Input Validation
Programming
User Interface

How do I make a textbox that only accepts numbers?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Creating a textbox that exclusively accepts numbers is a common requirement in software development and web development, particularly for applications that require user input in numeric form. This article will delve into various methods and techniques for creating a number-only textbox, emphasizing web development with HTML and JavaScript as well as desktop application development using languages like C# and Java.

Web Development

HTML and HTML5

For web applications, HTML5 provides a simplistic and efficient way to ensure a textbox only accepts numbers. This can be accomplished by using the input element with a type attribute set to number.

html
<input type="number" name="quantity" min="0" max="100">
  • Attributes:
    • type="number": Specifies that the input accepts only numeric values.
    • min and max: Define minimum and maximum values, respectively. Though optional, these attributes help in setting constraints for the numeric input.

Limitations

While the HTML5 approach is simple, it might not work uniformly across all browsers. Some browsers may allow non-numeric input when typing directly.

JavaScript

To provide a more robust solution, JavaScript can be used to validate input dynamically.

html
1<input id="numericInput" type="text" onkeypress="return isNumber(event)">
2
3<script>
4function isNumber(evt) {
5    let charCode = evt.which ? evt.which : evt.keyCode;
6    // Allow only digit keys and 'Backspace'
7    return (charCode >= 48 && charCode <= 57) || charCode === 8;
8}
9</script>
  • Explanation:
    • Using onkeypress, each keystroke is checked.
    • charCode determines the ASCII code of the key pressed.
    • Checks if the pressed key is between 48 ('0') and 57 ('9'), allowing only numeric characters.
    • Allows charCode === 8 for 'Backspace' to enable deletion.

CSS for Numeric Inputs

Though CSS cannot verify numeric input, it can be used to style valid or invalid entries for a better user experience.

css
input:invalid {
  border-color: red;
}
  • This CSS rule utilizes the :invalid pseudo-class to highlight inputs that fail to meet the HTML5 type="number" validation.

Desktop Application Development

C# WinForms

In C#, to create a textbox that only accepts numbers within a Windows Forms application, you can handle the KeyPress event.

csharp
1private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
2{
3    // Accept only digits ('0'-'9') and control characters
4    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
5    {
6        e.Handled = true;
7    }
8}
  • Explanation:
    • The KeyPress event is used to intercept each character input.
    • char.IsControl() enables special keys like 'Backspace'.
    • char.IsDigit() ensures that the input is a numeric digit.

Java Swing

In Java Swing, input constraints can be implemented using a DocumentFilter.

java
1import javax.swing.*;
2import javax.swing.text.*;
3
4public class NumberOnlyDocumentFilter extends DocumentFilter {
5    @Override
6    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
7        if (isNumeric(string)) {
8            super.insertString(fb, offset, string, attr);
9        }
10    }
11
12    @Override
13    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
14        if (isNumeric(text)) {
15            super.replace(fb, offset, length, text, attrs);
16        }
17    }
18
19    private boolean isNumeric(String str) {
20        try {
21            Integer.parseInt(str);
22            return true;
23        } catch (NumberFormatException e) {
24            return false;
25        }
26    }
27}
28
29// Usage in JTextField
30JTextField numericField = new JTextField();
31((AbstractDocument) numericField.getDocument()).setDocumentFilter(new NumberOnlyDocumentFilter());
  • Explanation:
    • DocumentFilter provides methods to examine and manipulate text entries.
    • insertString and replace methods are overridden to check if the input is numeric using isNumeric.
    • AbstractDocument is used to link the DocumentFilter to a JTextField.

Table: Summary of Techniques

TechniqueEnvironmentKey Concepts
HTML (input type="number")WebSimple syntax, cross-browser issues
JavaScript onkeypress validationWebCustomizable, handles key events independently
C# WinForms KeyPress handlerDesktop (C#)Uses char.IsDigit() and char.IsControl() for numeric and control keys
Java Swing DocumentFilterDesktop (Java)Manipulates input directly, uses Integer.parseInt() for numeric validation

With these tailored strategies, developers can ensure stringent numeric input validation across different platforms and environments, enhancing both usability and data integrity in applications.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions