How to perform form validation for a required field in HTML ?
1- Using required:
Syntax:
<input type="..." id="..." name="..." required>Example:
<!DOCTYPE html>
<html lang="en">
<body>
<p>Required Attribute</p>
<form>
<label>Name:</label>
<input type="text" required />
<label>Email:</label>
<input type="email" required />
<button style="margin-top: 5px">Submit</button>
</form>
</body>
</html>
<html lang="en">
<body>
<p>Required Attribute</p>
<form>
<label>Name:</label>
<input type="text" required />
<label>Email:</label>
<input type="email" required />
<button style="margin-top: 5px">Submit</button>
</form>
</body>
</html>
2- Using Maxlength attribute:
The maxlength attribute helps us to specify the maximum length of an input field in the form i.e. the maximum no. of characters that can be entered for the specific field. It can be used to make the maximum length of a telephone number in India as 10 digits so as to prevent any wrong input data submission.
Syntax:
<input type="..." id="..." name="..." maxlength="..."> Note: When the maxlength attribute is set, it will not allow the user to enter more characters than those specified.Example:
<!DOCTYPE html>
<html lang="en">
<body>
<p>Maxlength Attribute</p>
<form>
<label>Roll No.</label>
<input type="text" maxlength="10" required />
<label>Email:</label>
<input type="email" required />
<button style="margin-top: 5px">Submit</button>
</form>
</body>
</html>
<html lang="en">
<body>
<p>Maxlength Attribute</p>
<form>
<label>Roll No.</label>
<input type="text" maxlength="10" required />
<label>Email:</label>
<input type="email" required />
<button style="margin-top: 5px">Submit</button>
</form>
</body>
</html>