Skip to content
","url":"https://ez4code.com/snippets/html-form-validation","keywords":"html, form","author":{"@type":"Person","name":"EZ4Code Team"},"publisher":{"@type":"Organization","name":"EZ4Code","logo":{"@type":"ImageObject","url":"https://ez4code.com/logo.png"}},"datePublished":"2024-01-01","dateModified":"2026-08-01","image":"https://ez4code.com/og-image.png"}
HTML

Form Validation

HTML5 form validation.

By EZ4Code Team
htmlform

Code

<form id="myForm" novalidate>
    <div>
        <label for="name">Name *</label>
        <input type="text" id="name" name="name"
               required minlength="2" maxlength="50"
               placeholder="Please enter your name">
        <span class="error"></span>
    </div>

    <div>
        <label for="email">Email *</label>
        <input type="email" id="email" name="email"
               required
               pattern="[^@]+@[^@]+\.[^@]+"
               placeholder="[email protected]">
    </div>

    <div>
        <label for="age">Age</label>
        <input type="number" id="age" name="age"
               min="18" max="120" step="1" value="25">
    </div>

    <div>
        <label for="phone">Phone</label>
        <input type="tel" id="phone" name="phone"
               pattern="[0-9]{3}-[0-9]{4}-[0-9]{4}"
               placeholder="138-1234-5678">
    </div>

    <div>
        <label for="url">Personal Website</label>
        <input type="url" id="url" name="url"
               placeholder="https://example.com">
    </div>

    <button type="submit">Submit</button>
</form>

<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', (e) => {
    if (!form.checkValidity()) {
        e.preventDefault();
        form.reportValidity();
    }
});
</script>

Explanation

HTML5 form validation attributes required, pattern, min/max provide client-side validation; checkValidity() triggers validation.

More HTML Snippets