The HTML required attribute is a boolean attribute that specifies that a form control must be filled out or selected before the form can be submitted.
Definition and Usage
➔ The main use is to validate user input before submitting a form.
➔ If an attempt is made to submit a form that leaves a required field empty, the browser does the following:
- Prevents the form from being submitted.
- Visually highlight the empty field.
- Display a message prompting the user to fill in the field.
Syntax
//In HTML
<form action="/#" method="post">
Name<input type="text" id="name" name="name" required>
Email<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
//In Javascript
let element=document.querySelector("#name");
element.required = true;
//or
element.setAttribute("required", "");
// or
element.setAttribute("required", "required");
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| required | <input>, <select>, <textarea> |