Sitemap

required — HTML Attribute

2 min readJan 2, 2020

--

required attribute is like a gem kept inside of box (input field) which brings back customers’ attention to the box if they try to leave without putting anything inside it!!!

It is an HTML attribute used as required=“required” or required works with <input>, <select> and <textarea> elements. When required attribute is present on any of these elements, it specifies that the user must put something in the input filed before submitting the form.

It works with input types: text, search, url, tel, email, password, date, month, week, time, datetime-local, number, checkbox, radio, file.

Does not work when…

  1. required attribute does not works for input types hidden, button, range, color and image.

2. This attribute does not work if used outside of <form> element because “required” works only when submit event is fired and if the input element is not a part of any form the browser will not know what to validate on submit.

The required attribute is new in HTML5.

Example:

Get Mansi Singh’s stories in your inbox

Join Medium for free to get updates from this writer.

<form>
<input type=”text” name=”required Field” required=”required”>
<input type=”submit” value=”submit”>
</form>

Styling using CSS

:required is a pseudo class which can be used to style <input>, <select> and <textarea> elements if they include required attribute. The input filed will stay highlighted as per the styling defined for that element with :required pseudo class until user fills in some value inside it.

Example:

input:required {
border: 1px solid red;
}

:required styling applied until filed is empty
Input field highlighted when empty
:required styling goes away when user enter some value
No highlighting when it is non-empty

The pseudo class :optional matches the element which does not have required attribute included.

--

--