Form validation using HTML and JavaScript
Posted By: Akash Singh Published: 14, Jan 2024
Q4 - Create a contact form which accepts the following information: 1. Name, 2. Email, 3. Mobile and 4. Message. Following validations to be added. 1. Required, 2. Invalid values should not to be entered in any of the fields. Screenshot attached for reference. *
HTML
<body> <form name="myForm" onsubmit="return validateForm()" method="post"> <div class="myformlayout" id="name"> Name:<input type="text" name="fname" required ><span class="formerror"><b> </b></span> </div> <div class="myformlayout" id="email"> Email:<input type="email" name="femail" required><span class="formerror"><b> </b></span> </div> <div class="myformlayout" id="phone"> Phone:<input type="text" name="fphone" required><span class="formerror"><b> </b></span> </div> <div class="myformlayout">Message</div> <div class="myformlayout "> <textarea id="textarea" rows="10" cols="88" name="ftextbox" required> Enter you message here</textarea> </div> <input class="but" type="submit" value="Submit"> </form> </body>
CSS
<style> body { padding: 10px 50px; } .myformlayout { font-size: 18px; } .myformlayout input { width: 50%; padding: 5px 20px; border: 1px solid blue; margin-bottom: 14px; border-radius: 4px; font-size: 15px; display: flex; outline: none; } .formerror{ color: red; font-size: 18px; } @media screen and (max-width: 992px){ .myformlayout input{ width: 100%; padding: 0; height: 30px; } .myformlayout textarea{ max-width: 100%; } .myfomlayout{ max-width: 100%; } } .myfomlayout{ font-size: 18px; } .but{ background-color: blue; color: #fff; padding: 10px 20px 10px 15px; border: none; font-family: sans-serif; font-weight: 700; } </style>
JavaScript
<Script> function clearErrors(){ errors = document.getElementsByClassName('formerror'); for(let item of errors){ item.innerHTML = ""; } } function seterror(id, error){ element = document.getElementById(id); element.getElementsByClassName('formerror')[0].innerHTML = error; } function validateForm(){ var returnval = true; clearErrors(); //perform validation and if validtaion fails set the vale of return val to false var name = document.forms['myForm']["fname"].value; if (name.length<5){ seterror("name", "*Lenth of name is too short!"); returnval = false; } var email = document.forms['myForm']["femail"].value; if (email.length>55){ seterror("email", "*Lenth of email is too long!"); returnval = false; } var phone = document.forms['myForm']["fphone"].value; if (phone.length != 10){ seterror("phone", "*Phone no should be ten digit!"); returnval = false; } return returnval; } </Script>