Skip to content
HTML

Validación de Formularios

Validación de formularios HTML5.

#html#form

Code

html
<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>