Javascript Project to Validate Data inside Input Text Fields Using Regular Expression Full Project For Beginners






<html lang="en">
        <meta charset="utf-8" />
        <title>HTML DOM - Allow to enter particular characters only</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="" />
        <div style="align-items: center; display: flex; justify-content: center">
            <div style="margin: 4rem 0; width: 16rem">
                <div style="align-items: center; display: flex">
                    <input type="text" style="border: 1px solid #cbd5e0; padding: 0.5rem" id="input" />

            document.addEventListener('DOMContentLoaded', function () {
                const ele = document.getElementById('input');
                const state = {
                    value: ele.value,

                ele.addEventListener('keydown', function (e) {
                    const target =;
                    state.selectionStart = target.selectionStart;
                    state.selectionEnd = target.selectionEnd;

                ele.addEventListener('input', function (e) {
                    const target =;

                    if (/^[0-9\s]*$/.test(target.value)) {
                        state.value = target.value;
                    } else {
                        // Users enter the not supported characters
                        // Restore the value and selection
                        target.value = state.value;
                        target.setSelectionRange(state.selectionStart, state.selectionEnd);

Leave a Reply