user1534462
user1534462

Reputation: 51

Html 5 Form validation without Form

Can a html5 form validation

<form>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</form>

can it be done without a Form

<div>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</div>

Upvotes: 5

Views: 5073

Answers (2)

dani24
dani24

Reputation: 2288

If you want to see the errors in the page, instead of just receiving a boolean with the validation result, you can use:

document.gelElementById('email').reportValidity();

Upvotes: 1

user663031
user663031

Reputation:

Yes, use the constraint validation API. See http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api. For instance, you can call element . checkValidity(). See also https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation or https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity. For example:

var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...

or use the invalid event which is fired when checkValidity() fails:

email.addEventListener("invalid", function() { alert("Email invalid"); });

You can use setCustomValidity to set the validity status and/or error message:

if (!email.value) email.setCustomValidity("Email is missing");

Upvotes: 5

Related Questions