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.
Syntax
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.
Example
Let us look at an example for the input text required property −
<!DOCTYPE html> <html> <body> <h1>Input Text required property</h1> <form action="/Sample_page.php"> USERNAME: <input type="text" id="USR" name=”user_name” required> <input type="submit"> </form> <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> <script> function checkReq() { var Req=document.getElementById("USR").required; if(Req==true) document.getElementById("Sample").innerHTML="The text field must be filled before submitting"; else document.getElementById("Sample").innerHTML="The text field is optional and can be left blank by the user"; } </script> </body> </html>
Output
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 −