HTML DOM Input Text required property

HTMLWeb DevelopmentFront End Technology

The HTML DOM input Text required property is associated with the required attribute of an <input> element. The required property is used for setting and returning if it is necessary to fill some text field or not before the form is submitted to the server. This allows the form to not submit if a text field with required attribute is left empty by the user.


Following is the syntax for −

Setting the required property −

textObject.required = true|false

Here, true represents the text field must be filled while false represents its optional to fill the field before submitting the form.


Let us look at an example for the input text required property −

Live Demo

<!DOCTYPE html>
<h1>Input Text required property</h1>
<form action="/Sample_page.php">
USERNAME: <input type="text" id="USR" name=”user_name” required>
<input type="submit">
<p>Check if the above field is mandatory to be filled or not by clicking the below button</p>
<button onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
   function checkReq() {
      var Req=document.getElementById("USR").required;
         document.getElementById("Sample").innerHTML="The text field must be filled before submitting";
      document.getElementById("Sample").innerHTML="The text field is optional and can be left blank by the user";


This will produce the following output −

On clicking the CHECK button −

If you will click “Submit” now without entering the username, a warning would be visible and it won’t allow you to submit the form −

Updated on 19-Feb-2021 05:31:10