Why this is asked
This question tests a candidate's knowledge of fundamental HTML capabilities and their approach to user experience and client-side validation. It assesses whether they utilize browser-native features before resorting to JavaScript, understanding the balance between convenience, accessibility, and robust server-side validation. Native validation is an often-overlooked yet powerful tool for improving form UX with minimal effort.
HTML5 introduced robust native form validation capabilities directly in the browser, reducing the need for extensive client-side JavaScript for basic checks. Attributes like required, pattern, minlength, maxlength, min, max, and type (e.g., email, url, number) allow browsers to automatically validate user input. If validation fails on submission, the browser prevents form submission and displays an error message near the invalid field, often with a helpful tooltip. This improves user experience by providing immediate feedback and reduces developer effort.
<form>
<label for="username">Username (min 3 chars):</label>
<input type="text" id="username" name="username" required minlength="3">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
title="Please enter a valid email address (e.g., user@example.com)">
<label for="age">Age (18-99):</label>
<input type="number" id="age" name="age" min="18" max="99">
<button type="submit">Submit</button>
</form>
Gotchas: While native validation is great for initial feedback, it's easily bypassed (e.g., by disabling JavaScript or using novalidate on the form). Therefore, server-side validation is always required for data integrity and security. Customizing the default browser error messages and styling can be challenging and inconsistent across browsers, often requiring JavaScript (setCustomValidity) for a consistent look and feel. The novalidate attribute on a form can completely disable native validation, which is useful when implementing custom JS validation frameworks.
References: MDN Web Docs: Form data validation, HTML Living Standard: Forms
