30. Input Validation Attributes (required, readonly, disabled)
required, placeholder, readonly, disabled, min, max, pattern
Real-life analogy
Just as an exam form has a red star (*) showing that a field is mandatory (required), these attributes do the same thing.
Explanation
The main attributes that control an input field:
required: The form will not submit without it.placeholder: Light hint text shown inside the box.readonly: The user can only read it and cannot change it (but the data will go to the server).disabled: The box becomes completely inactive (grey) (the data does not go to the server).minandmax: The minimum and maximum limits for a number or date.
Golden rules
- Remember the difference between
readonlyanddisabled: the data of readonly is submitted, that of disabled is not.
Common mistake
Treating placeholder as a substitute for label. A label is mandatory for screen readers.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 20px;">
<form style="max-width: 260px;">
<label style="font-size: 12px; font-weight: bold;">Name (required *):</label>
<input type="text" placeholder="Enter name..." required
style="width: 100%; padding: 6px; margin: 3px 0 8px 0; border: 1px solid #cbd5e1; border-radius: 4px; box-sizing: border-box;">
<label style="font-size: 12px; font-weight: bold;">Roll number (Readonly):</label>
<input type="text" value="10582" readonly
style="width: 100%; padding: 6px; margin: 3px 0 10px 0; background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 4px; box-sizing: border-box;">
<button type="submit" style="background: #0284c7; color: white; border: none; padding: 8px 14px; border-radius: 4px; cursor: pointer;">Submit</button>
</form>
</body>
</html>
Quick quiz
Which attribute makes an input box inactive (grey) on screen so that its data is not submitted?
- readonly
- disabled
- hidden
- locked
Show answer
Answer: disabled
The disabled attribute turns the input off, and its value is not sent in the form submission.