HTML DOM Input Password required property

HTMLWeb DevelopmentFront End Technology

The HTML DOM input password 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 password field or not before the form is submitted to the server. This allows the form to not submit if a password 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 password required property −

<!DOCTYPE html>
<html>
<body>
<h1>Input password required property</h1>
<p>Check if the above field is mandatory to be filled or not by clicking the below button</p>
<form action="/Sample_page.php">
Password: <input type="password" id="PASS1" name=”passW” required>
<input type="submit">
</form>
<br>
<button onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
<script>
   function checkReq() {
      var Req=document.getElementById("PASS1").required;
      if(Req==true)
         document.getElementById("Sample").innerHTML="The password field must be filled before submitting";
      else
         document.getElementById("Sample").innerHTML="The password 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 the required property is set true and you click submit −

In the above example −

We have first created an input password field with id “PASS1”, name “passW” and required attribute set to true.The password field is contained inside a form with action=”Sample_page.php” which specifies where to submit the form data when clicked on the submit button.

<form action="/Sample_page.php">
Password: <input type="password" id="PASS1" name=”passW” required>
<input type="submit">
</form>

We have then created a button CHECK that will execute the checkReq() method when clicked by the user −

<button onclick="checkReq()">CHECK</button>

The checkReq() uses the getElementById() method to get the input element with type password and get its required property which in our case returns true. The returned boolean value is assigned to a variable Req and based on whether the returned value is true or false we display appropriate message in the paragraph with id “Sample” using its innerHTML property −

function checkReq() {
   var Req=document.getElementById("PASS1").required;
   if(Req==true)
      document.getElementById("Sample").innerHTML="The password field must be filled before submitting";
   else
      document.getElementById("Sample").innerHTML="The password field is optional and can be left blank by theuser";
}
raja
Published on 22-Aug-2019 09:04:18
Advertisements