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
Accessible Form with Inputs
Build an accessible HTML form with labels, inputs, select, and checkbox.
Table with Thead Tbody Tfoot
Structure tabular data with thead, tbody, tfoot, and caption in HTML.
Responsive Images and Video
Embed responsive images with srcset, video, audio, and figure in HTML.
Links Anchors and Download
Create internal, external, anchor, email, phone, and download links in HTML.
Semantic Tags
HTML5 semantic structure.
SVG
Scalable Vector Graphics.