Create Contact Us Form Validate fields using javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Contact Us Form Validate fields using javascript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<style>
#main{
float:left;
display:inline;
width:470px;
margin-left:55px;
}
form{
margin:1em 0;
}
fieldset{
border:none;
margin:0;
background:#f1f1f1;
border:5px solid #e7e7e7;
padding:1em 15px;
}
legend{
display:none;
}
label{
float:left;
clear:both;
width:120px;
margin-right:10px;
margin-top:5px;
text-align:right;
}
input, textarea{
width:250px;
border:1px solid #ccc;
padding:5px;
margin:5px 0;
}
textarea{
height:80px;
overflow:auto;
}
form p{
clear:both;
margin:0;
}
form h3{
margin:1em 0 .5em 0;
font-size:25px;
}
.submit{
text-align:right;
}
span.error{
display:block;
color:#a50000;
font-weight:bold;
margin-left:130px;
}
</style>
<script>
this.form = function(){
this.validate = function(name, email, message){
$("span.error").remove();
var valid = true;
//name
if(name == "") {
error($("#name"),"Please tell us your name.")
valid = false;
};
//email
if(!checkEmail(email)) {
error($("#email"),"We need a valid email address.")
valid = false;
};
//messgae
if(message == "") {
error($("#message"),"Please write a message.")
valid = false;
};
return valid;
};
this.checkEmail = function(str){
var regEx = /^[^@]+@[^@]+.[a-z]{2,}$/;
return (str.search(regEx) != -1);
};
this.error = function(obj,text){
var parent = $(obj).parent();
parent.append("<span class=\"error\">"+ text +"</span>");
$("span.error",parent).hide().show("fast");
};
$("#contactForm button").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
if(validate(name, email, message)) return true;
return false;
});
};
this.init = function() {
form();
};
$(document).ready(function(){
init();
});
</script>
<div id="main">
<h2>Contact us</h2>
<p>Nunc volutpat nisi nec leo. Fusce accumsan, mi ac posuere rhoncus,
arcu orci tristique leo, vitae consequat.</p>
<form id="contactForm" action="send.php" method="post">
<fieldset><legend>Contact form</legend>
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name" size="30" />
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" size="30" />
</p>
<p>
<label for="message">Message</label>
<textarea name="message" id="message" rows="10" cols="30"></textarea>
</p>
<p class="submit">
<button type="submit">Send</button>
</p>
</fieldset>
</form>
</div>
</body>
</html>
//sent.php
<p><h1>Email Succesfully sent</h1></p>
VIDEO