Create JavaScript program for the following form validations. Make use of HTML5 properties to do the following validations:

1) Name, address, contact number and email are required 

2) Address field should show the hint value which will disappear when form. field gets focus or key press event.

3) Telephone number should be maximum 10 digit number only.

4) Email field should contain valid email address, @ should appear only once and not at the beginning dot. 

5) Make use of pattern attribute for email to accept lowercase, uppercase alphabets, digits and specified symbols. 



Create JavaScript program for the following form validations. Make use of HTML5 properties to do the following validations:


Html Code:- 

<form>

  <label for=”name”>Name:</label>

  <input type=”text” id=”name” required>

  

  <label for=”address”>Address:</label>

  <input type=”text” id=”address” required placeholder=”Enter your address”>


  <label for=”phone”>Phone:</label>

  <input type=”tel” id=”phone” pattern=”[0-9]{10}” required>


  <label for=”email”>Email:</label>

  <input type=”email” id=”email” pattern=”[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$” required>

  

  <button type=”submit”>Submit</button>

</form>

 



Javascript code:- 


<script>

  const addressInput = document.getElementById(“address”);


  addressInput.addEventListener(“focus”, function(event) {

    event.target.placeholder = “”;

  });


  addressInput.addEventListener(“blur”, function(event) {

    event.target.placeholder = “Enter your address”;

  });


  const phoneInput = document.getElementById(“phone”);

  

  phoneInput.addEventListener(“input”, function(event) {

    if (event.target.value.length > 10) {

      event.target.value = event.target.value.slice(0, 10);

    }

  });


  const emailInput = document.getElementById(“email”);


  emailInput.addEventListener(“input”, function(event) {

    const emailRegex = /^[^@.].*@[^@]*.[^@]*$/;

    if (!emailRegex.test(event.target.value)) {

      event.target.setCustomValidity(“Invalid email address.”);

    } else {

      event.target.setCustomValidity(“”);

    }

  });

</script>

Leave a Comment