HTML onbeforeinput Event Attribute
Description
The onbeforeinput attribute is used to specify JavaScript code that should run just before the browser processes changes to the value of an <input> or <textarea> element. This event occurs before any text is inserted, deleted, or replaced by the user’s action.
It allows developers to intercept input actions, perform validation, or even prevent the input from happening using event.preventDefault().
Applicable Elements
<input>(types that accept text:text,search,url,tel,email,password, etc.)<textarea>[contenteditable]elements (e.g.,<div contenteditable="true">)
Event Timing
- Fires before the DOM value changes.
- Happens after the user action starts but before the input is committed.
- Can cancel the action to prevent the change.
Event Object
When onbeforeinput triggers, it receives an InputEvent object with useful properties:
data: The string being inserted (for insertions) ornullfor deletions.inputType: Type of input action. Examples:"insertText"– user typed text"deleteContentBackward"– user pressed backspace"insertFromPaste"– user pasted text"insertLineBreak"– user pressed Enter
isComposing: Indicates if the event is part of IME (Input Method Editor) composition for complex characters.target: The element receiving input.
Key Features
Prevent user input:
function preventNumbers(event) { if (/d/.test(event.data)) { event.preventDefault(); // blocks the input alert("Numbers are not allowed!"); } }<input type="text" onbeforeinput="preventNumbers(event)">Detect input types: You can check
event.inputTypeto determine if the action is a deletion, insertion, paste, or undo/redo.Works with contenteditable: Useful for rich-text editors to filter or validate user input.
Example
<textarea onbeforeinput="handleBeforeInput(event)" rows="5" cols="40"></textarea>
<script>
function handleBeforeInput(event) {
console.log("Input type:", event.inputType);
console.log("Data:", event.data);
// Example: Prevent digits
if (/d/.test(event.data)) {
event.preventDefault();
alert("Digits are not allowed!");
}
}
</script>
Explanation:
- When the user types, the function logs the input type and data.
- If a digit is typed,
preventDefault()stops it from appearing in the textarea.
Practical Use Cases
- Prevent invalid characters (numbers, symbols) in form fields.
- Custom input validation for rich text editors.
- Intercept paste or drop events for security (like blocking scripts in
contenteditable). - Logging or analytics on user input.
Syntax
<element onbeforeinput="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
Browser Support
The following information will show you the current browser support for the HTML onbeforeinput event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 27th December 2025
