Form Validation using Javascript Regular Expression? - javascript

I'm creating a registration form which contains userid, name, email, password, confirm password and affiliation. These fields are validated using regular expression in javascript. I want the error to be displayed in the form and I'm using span tag to achieve this. I don't know where I'm going wrong since its not being validated.
function validation() {
var userid = document.getElementById('userid').value;
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var psw = document.getElementById('psw').value;
var psw_repeat = document.getElementById('psw_repeat').value;
var usercheck = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/;
var fnamecheck = /^[A-Za-z. ]{3,20}$/;
var lnamecheck = /^[A-Za-z. ]{3,20}$/;
var emailcheck = /^[A-Za-z_]{3,}#[A-Za-z]{3,}[.]{1}[A-Za-z.]{2,6}$/;
var pswcheck = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9##$%^&*]{8,15}$/;
if (usercheck.test(userid)) {
document.getElementById('usererror').innerHTML = "";
} else {
document.getElementById('usererror').innerHTML = "**User id is invalid";
return false;
}
if (fnamecheck.test(fname)) {
document.getElementById('fnameerror').innerHTML = "";
} else {
document.getElementById('fnameerror').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (emailcheck.test(email)) {
document.getElementById('mail').innerHTML = "";
} else {
document.getElementById('mail').innerHTML = "**Email-id is invalid";
return false;
}
if (pswcheck.test(psw)) {
document.getElementById('pass').innerHTML = "";
} else {
document.getElementById('pass').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (psw.match(psw_repeat)) {
document.getElementById('conpass').innerHTML = "";
} else {
document.getElementById('conpass').innerHTML = "**Password doesnot match";
return false;
}
}
<html>
<body>
<form id="reg" method="post" onsubmit="return validation()">
<legend><b>Create an account</b></legend>
<div class="form-group">
<label for="userid">User id</label>
<input type="text" placeholder="Enter your User id" class="form- control" name="userid" id="userid">
<span id="usererror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="fname">First Name</label>
<input type="text" placeholder="Enter your First name" class="form- control" name="fname" id="fname">
<span id="fnameerror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="email">Email id</label>
<input type="email" placeholder="Enter your Email-id" class="form- control" name="email" >
<span id="mail" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw">Password</label>
<input type="password" placeholder="Enter Password" class="form- control" id="psw">
<span id="pass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw_repeat">Confirm Password</label>
<input type="password" placeholder="Re-enter Password" class="form-control" id="psw_repeat" >
<span id="conpass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<div class="dropdown">
<label for="affiliation">Affiliation</label>
<select class="form-control">
<option value="alumni" name="affiliation">Alumni</option>
<option value="faculty" name="affiliation">Faculty</option> <option value="student" name="affiliation">Student</option>
</select>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="submit" name="submit">Register</button>
<button type="reset" class="btn btn-danger">Cancel</button>
</div>
</form>
</body>
</html>

#lname does not exist, so document.getElementById('lname') is null; trying to look up .value on that is breaking your function.

lname this filed is missing in js file and also some filed not have id value in html file.
<html>
<body>
<form id="reg" method="post" onsubmit="return validation()">
<legend><b>Create an account</b></legend>
<div class="form-group">
<label for="userid">User id</label>
<input type="text" placeholder="Enter your User id" class="form-control" name="userid" id="userid">
<span id="usererror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="fname">First Name</label>
<input type="text" placeholder="Enter your First name" class="form-control" name="fname" id="fname">
<span id="fnameerror" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="email">Email id</label>
<input type="email" placeholder="Enter your Email-id" class="form-control" name="email" id="email">
<span id="mail" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw">Password</label>
<input type="password" placeholder="Enter Password" class="form-control" id="psw">
<span id="pass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<label for="psw_repeat">Confirm Password</label>
<input type="password" placeholder="Re-enter Password" class="form-control" id="psw_repeat">
<span id="conpass" class="text-danger font-weight-bold"></span>
</div>
<div class="form-group">
<div class="dropdown">
<label for="affiliation">Affiliation</label>
<select class="form-control">
<option value="alumni" name="affiliation">Alumni</option>
<option value="faculty" name="affiliation">Faculty</option>
<option value="student" name="affiliation">Student</option>
</select>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="submit" name="submit">Register</button>
<button type="reset" class="btn btn-danger">Cancel</button>
</div>
</form>
</body>
</html>
//Script file
function validation() {
var userid = document.getElementById('userid').value;
var fname = document.getElementById('fname').value;
// var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var psw = document.getElementById('psw').value;
var psw_repeat = document.getElementById('psw_repeat').value;
var usercheck = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$/;
var fnamecheck = /^[A-Za-z. ]{3,20}$/;
//var lnamecheck = /^[A-Za-z. ]{3,20}$/;
var emailcheck = /^[A-Za-z_]{3,}#[A-Za-z]{3,}[.]{1}[A-Za-z.]{2,6}$/;
var pswcheck = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9##$%^&*]{8,15}$/;
if (usercheck.test(userid)) {
document.getElementById('usererror').innerHTML = "";
} else {
document.getElementById('usererror').innerHTML = "**User id isinvalid";
return false;
}
if (fnamecheck.test(fname)) {
document.getElementById('fnameerror').innerHTML = "";
} else {
document.getElementById('fnameerror').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (emailcheck.test(email)) {
document.getElementById('mail').innerHTML = "";
} else {
document.getElementById('mail').innerHTML = "**Email-id is invalid";
return false;
}
if (pswcheck.test(psw)) {
document.getElementById('pass').innerHTML = "";
} else {
document.getElementById('pass').innerHTML = "**Should not contain digits and special characters";
return false;
}
if (psw.match(psw_repeat)) {
document.getElementById('conpass').innerHTML = "";
} else {
document.getElementById('conpass').innerHTML = "**Password doesnot match";
return false;
}
}

Related

HTML form showing error even after entering correct values

I have a contact form including validations. HTML form shows an error on entering wrong values but after correcting the values and entering appropriate data it continues to show the same error. I am validating the form using pattern attribute in the form.
The code below includes the form and the script which is used for validation.
Here is the part of the document:
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Create Account</h1>
<div>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" pattern='^[a-zA-Z ]*$' autofocus required/>
</div>
<!--<?php if(isset($msg_name)) echo "<script>alert('$msg_name')</script>";?>-->
<div>
<input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus required />
</div>
<!--<?php if(isset($msg_username)) echo "<script>alert('$msg_username')</script>";?>-->
<div>
<input type="email" name="email" id="email" class="form-control" placeholder="Email" pattern='^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$' autofocus required/>
</div>
<!--<?php if(isset($msg_email)) echo "<script>alert('$msg_email')</script>";?>-->
<div>
<input type="text" name="phone" id="phone" class="form-control" placeholder="PhoneNumber" autofocus required />
</div>
<div>
<input type="password" name="password" id="password1" class="form-control" placeholder="Password" autofocus required />
<input type="checkbox" onclick="signup_pass()">Show Password
</div><br>
<!--<?php if(isset($msg_password)) echo "<script>alert('$msg_password')</script>";?>-->
<div>
<input class="btn btn-default submit" type="submit" name="submit" value="SIGNUP" >
<?php if(isset($error)) echo "<script>alert('$error')</script>";?>
<?php if(isset($message)) echo "<script>alert('$message')</script>";?>
</div>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">Already a member ?
Log in
</p>
<div class="clearfix"></div>
<br />
<div>
<h1> Elegocart!</h1>
<p>©2018 All Rights Reserved.Privacy and Terms</p>
</div>
</div>
</form>
</section>
</div>
</div>
</div>
<script>
function login_pass() {
var x = document.getElementById("password");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function signup_pass() {
var x = document.getElementById("password1");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
var name = document.getElementById('name');
var username = document.getElementById('username');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
var password = document.getElementById('password1');
name.oninvalid = function(event)
{
event.target.setCustomValidity("Name should include only alphabets and white space");
}
username.oninvalid = function(event)
{
event.target.setCustomValidity("a-z, 0-9, underscore, hyphen");
}
email.oninvalid = function(event)
{
event.target.setCustomValidity("Must be of valid email format");
}
phone.oninvalid = function(event)
{
event.target.setCustomValidity("Enter aaa valid phone number");
}
password.oninvalid = function(event)
{
event.target.setCustomValidity("Password : must contain uppercase,lowercase,numbers and special characters , and shouldbe minimum of 8 characters long");
}
</script>
Probably your function is wrong try something like this :
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Unable to validate more than the first entry in a form

I am trying to validate a form using Javascript but as of right now, it is validating the first form entry and ignoring the rest. If I have less than 6 characters, it'll stop the form from submitting. Once I add more characters, it'll act like the form is fine and submit it, even if everything else is wrong.
HTML:
<form class="form-horizontal" onsubmit="return validator(this);">
<div class="form-group">
<label class="control-label col-xs-3" for="userName">Username:</label>
<div class="col-xs-9">
<!-- USERNAME --><input type="text" class="form-control" id="userName" placeholder="Username"maxlength="50">
<p id="userNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password">Password:</label>
<div class="col-xs-9">
<!-- PASS1 --><input type="password" class="form-control" id="Password" placeholder="Password"maxlength="50">
<p id="password1Emsm"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="Password2">Re-enter Password:</label>
<div class="col-xs-9">
<!-- PASS2 --><input type="password" class="form-control" id="Password2" placeholder="Re-enter Password"maxlength="50">
<p id="password2Emsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="firstName">First Name:</label>
<div class="col-xs-9">
<!-- FIRSTNAME --><input type="text" class="form-control" id="firstName" placeholder="First Name"maxlength="50">
<p id="firstNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="lastName">Last Name:</label>
<div class="col-xs-9">
<!-- LASTNAME --><input type="text" class="form-control" id="lastName" placeholder="Last Name"maxlength="50">
<p id="lastNameEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="zipCode">Zip Code:</label>
<div class="col-xs-9">
<!-- ZIPCODE --><input type="text" class="form-control" id="zipCode" placeholder="Zip Code" maxlength="10">
<p id="zipCodeEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="phoneNumber">Phone Number:</label>
<div class="col-xs-9">
<input type="tel" class="form-control" id="phoneNumber" placeholder="Phone Number"maxlength="12">
<p id="phoneNumberEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-3" for="inputEmail">Email Address:</label>
<div class="col-xs-9">
<!-- EMAILADDRESS --><input type="email" class="form-control" id="inputEmail" placeholder="email#address.com"maxlength="100">
<p id="emailEmsg"style="margin:0px;color:red;font-weight:bold;"></p>
</div>
</div>
<div class="form-group"><!-- BUTTONS -->
<div class="col-xs-offset-3 col-xs-9">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</form>
JS:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var password2 = document.getElementById("Password2");
var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var email = document.getElementById("inputEmail");
var passwordFormat = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var emailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
return false;
}
else if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
return false;
}
else if (!password.value.match(passwordFormat)) {
document.getElementById("password1Emsg").innerHTML = "Enter correct password format.";
return false;
}
else if (password.value != password2.value) {
document.getElementById("password2Emsg").innerHTML = "Passwords do not match.";
return false;
}
else if (email.value.length < 1) {
document.getElementById("emailEmsg").innerHTML = "Please enter an email.";
return false;
}
else if (!email.value.match(emailFormat)) {
document.getElementById("emailEmsg").innerHTML = "Enter correct email format.";
return false;
}
else {
return true;
}
}
I have removed all the elses and have removed the return statement at the bottom and it made no difference to how it funtioned.
Remove all the else if clasues, replace them by pure if and remove the return statement.
Now your code at least, will run through and display all error messages, instead of only the first one.
Now you will need a flag, that signifies, that your form is invalid and disables the Submit button:
function validator(form) {
var userName = document.getElementById("userName");
var password = document.getElementById("Password");
var isFormValid = true;
if (userName.value.length < 6) {
document.getElementById("userNameEmsg").innerHTML = "Must have at least 6 characters.";
isForValid = false;
}
if (password.value.length == 0) {
document.getElementById("password1Emsg").innerHTML = "Please enter a password.";
isForValid = false;
}
/**check if form is Vald **/
if(!isFormValid){
//disable submit button
}
}
But if you can avoid it: use as much, of the built-in function of html as possible. There is no reason you could not just use
<input type="email" id="emailField" required />
and then call document.getElementById('emailField').checkValidity();

JavaScript Onclick is not working in tag

HTML:
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="new User().register()">REGISTER</div>
</div>
</form>
Js File
var User = function() {
var self = this;
self.register = function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/
var regEight = /^8[0-9].*$/
if($("#empId").val() =='')
{
alert(Language.InvalidEmployeeId);
return false;
}
if(mobile =='')
{
alert(Language.EmptyMobileNumber);
return false;
}
}
};
if i write a coding for click event like below its working when i use OnClick event function is not calling
$("#regBtn").click(function ()
{
new User().register();
})
how to make the onclick work.. thanks in advance
In onclick call a function that does new User().register().
Do not write literal expression, wrap that expression in function and call that function.
try with this code
$("#regBtn").click(function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/;
var regEight = /^8[0-9].*$/;
if ($("#empId").val() == '') {
// alert(Language.InvalidEmployeeId);
console.log("InvalidEmployeeId");
return false;
}
if (mobile == '') {
//alert(Language.EmptyMobileNumber);
console.log("Empty mobile number");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="javascript:if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn">REGISTER</div>
</div>
</form>
</div>
Do something like this...
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="registerUser()">REGISTER</div>
</div>
</form>
</div>
Java script
function registerUser(){
new User().register();
}
In this case the function registerUser() is re-usable as you commented above "Actually i want to make use of the onclick event so that function can be reused if i give a id i cant reuse that in another page".

how to set focus on an input field when an error occurred during the form submission

1. I am creating a form validation everything fine, but when an error occurred during the form submission it should be focused on that field.
2. thing is an error message. I am using span for showing error message, but when page loaded span also making some space below the input field that is making a distorted. how to hide it when the page loaded and if we don't fill any field show error message show.
Here is my code:
HTML
<form name="registration" id="form" action="contact.php" method="post" onsubmit="return validateform();">
<div class="form-group">
<div class="input-group col-xs-12 text-left">
<label for="InputName">Full Name:<span style="color:red;">*</span></label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<br>
<span id="f_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputEmail">Email Address:<span style="color:red;">*</span></label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
<br>
<span id="e_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputCompany">Company:<span style="color:red;">*</span></label>
<input type="text" name="company" id="company" class="form-control" placeholder="Company">
<br>
<span id="c_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="ProjectDescription">Project Description:<span style="color:red;">*</span></label>
<input name="project" id="project" type="text" class="form-control" placeholder="Project Description">
<br>
<span id="p_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputMessage">Message:<span style="color:red;">*</span></label>
<input type="text" name="message" id="message" class="form-control" placeholder="I love a team that...">
<br>
<span id="m_error_msg"></span>
</div>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-success btn-block" value="Go">
</div>
</form>
JavaScript
function validateform() {
var fullname = document.registration.name.value;
var emailadd = document.registration.email.value;
var company = document.registration.company.value;
var project = document.registration.project.value;
var message = document.registration.message.value;
if (fullname === null || fullname === "") {
document.getElementById('f_error_msg').innerHTML = "Please enter Full Name";
fullname.focus();
return false;
document.getElementById('f_error_msg').style.display = "none";
}
var atposition = emailadd.indexOf("#");
var dotposition = emailadd.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= emailadd.length) {
document.getElementById('e_error_msg').innerHTML = "Please enter a valid e-mail address \n atpostion:" + atposition + "\n dotposition:" + dotposition;
emailadd.focus();
return false;
document.getElementById('e_error_msg').style.display = "none";
}
if (company === null || company === "") {
document.getElementById('c_error_msg').innerHTML = "Please enter your company name";
company.focus();
return false;
document.getElementById('c_error_msg').style.display = "none";
}
if (project === null || project === "") {
document.getElementById('p_error_msg').innerHTML = "Please enter your project name";
project.focus();
return false;
document.getElementById('p_error_msg').style.display = "none";
}
if (message === null || message === "") {
document.getElementById('m_error_msg').innerHTML = "Please enter your message here.";
message.focus();
return false;
document.getElementById('m_error_msg').style.display = "none";
}
}
To set focus you can use:
document.getElementById('name').focus();
If name field has an error.
For span space issue, use display:none initially and when you get the error specify display:inline for that particular error span.
You should use focus() function, check working example bellow.
Hope this helps.
function validateform() {
var fullname = document.registration.name.value;
var emailadd = document.registration.email.value;
var company = document.registration.company.value;
var project = document.registration.project.value;
var message = document.registration.message.value;
if (fullname === null || fullname === "") {
resetErrorMsg();
document.getElementById('f_error_msg').innerHTML = "Please enter Full Name";
document.registration.name.focus();
document.getElementById('f_error_msg').style.display = "block";
return false;
}else{
document.getElementById('f_error_msg').style.display = "none";
}
var atposition = emailadd.indexOf("#");
var dotposition = emailadd.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= emailadd.length) {
resetErrorMsg();
document.getElementById('e_error_msg').innerHTML = "Please enter a valid e-mail address \n atpostion:" + atposition + "\n dotposition:" + dotposition;
document.registration.email.focus();
document.getElementById('e_error_msg').style.display = "block";
return false;
}else{
document.getElementById('e_error_msg').style.display = "none";
}
if (company === null || company === "") {
resetErrorMsg();
document.getElementById('c_error_msg').innerHTML = "Please enter your company name";
document.registration.company.focus();
document.getElementById('c_error_msg').style.display = "block";
return false;
}else{
document.getElementById('c_error_msg').style.display = "none";
}
if (project === null || project === "") {
resetErrorMsg();
document.getElementById('p_error_msg').innerHTML = "Please enter your project name";
document.registration.project.focus();
document.getElementById('p_error_msg').style.display = "block";
return false;
} else{
document.getElementById('p_error_msg').style.display = "none";
}
if (message === null || message === "") {
resetErrorMsg();
document.getElementById('m_error_msg').innerHTML = "Please enter your message here.";
document.registration.message.focus();
document.getElementById('m_error_msg').style.display = "block";
return false;
} else{
document.getElementById('m_error_msg').style.display = "none";
}
}
function resetErrorMsg(){
document.getElementById('f_error_msg').style.display = "none";
document.getElementById('e_error_msg').style.display = "none";
document.getElementById('c_error_msg').style.display = "none";
document.getElementById('p_error_msg').style.display = "none";
document.getElementById('m_error_msg').style.display = "none";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<form name="registration" id="form" action="contact.php" method="post" onsubmit="return validateform();">
<div class="form-group">
<div class="input-group col-xs-12 text-left">
<label for="InputName">Full Name:<span style="color:red;">*</span></label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<br>
<span id="f_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputEmail">Email Address:<span style="color:red;">*</span></label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
<br>
<span id="e_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputCompany">Company:<span style="color:red;">*</span></label>
<input type="text" name="company" id="company" class="form-control" placeholder="Company">
<br>
<span id="c_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="ProjectDescription">Project Description:<span style="color:red;">*</span></label>
<input name="project" id="project" type="text" class="form-control" placeholder="Project Description">
<br>
<span id="p_error_msg"></span>
</div>
<div class="input-group col-xs-12 text-left">
<label for="InputMessage">Message:<span style="color:red;">*</span></label>
<input type="text" name="message" id="message" class="form-control" placeholder="I love a team that...">
<br>
<span id="m_error_msg"></span>
</div>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-success btn-block" value="Go">
</div>
</form>

Form validation with AJAX return

I have a contact form that, when submit is clicked, I want to be validated.
If all fields return valid, then I want AJAX to return a Processing message, then, when successful, a message appears with the imputed name.
My Form content is:
<form onsubmit="return validateForm">
<input id="fname" class="textbox" name="fname" placeholder="First Nname" type="text" required="required" /><p>
<input id="sname" class="textbox" name="sname" placeholder="Surname" type="text" required="required" /><p>
<input id="email" class="textbox" name="email" placeholder="Email Address" type="email" required="required" /><p>
<input id="number" class="textbox" name="number" placeholder="Contact Number" type="email" /><p>
<textarea rows="10" id="message" class="textarea" name="message" placeholder="Message" required="required" ></textarea><p>
<input fname="myBtn" class="button" type="submit" value="Submit" onClick="javascript:ajax_post();">
My Form Validation content is:
function validateForm()
{
var fname=document.forms["Form"]["fname"].value;
var sname=document.forms["Form"]["sname"].value;
var x=document.forms["Form"]["email"].value;
var telnum=document.forms["Form"]["telnum"].value;
var message=document.forms["Form"]["message"].value;
if(fname==null||fname=="")
{
alert("please enter your first name");
return false;
}
if(sname==null||sname=="")
{
alert("please enter your surname");
return false;
}
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if(atpos<1||dotpos<atpos+2||dotpos+2>x.lenght)
{
alert("Not a valid email address.");
return false;
}
if(message==null||message=="")
{
alert("please enter a message");
return false;
}
}
The AJAX Script is:
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "/additional/formfeedback.php";
var fname = document.getElementById("fname").value;
var vars = "fname="+fname;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "Processing...";
}
And the returned PHP is:
<?php
echo 'Thank you '. $_POST['fname'] . ', we have recieved your message and will be back in touch shortly';
?>
When the Submit button is clicked, the PHP content is returned, then the validation starts - obviously too late.
How do I get this to validate correctly, then carry out the AJAX script? I don't want to use any additional libraries, such a jQuery. Thanks in advance.
you should set the validation to the submit button, and then at the bottom of the validation script, call the ajax script.
Call ajax_post at the end of your validateForm method.
One point ... you don't need "javascript:" in an onclick. It's already expecting javascript.
Also, if you want to submit data with Ajax, change the button to type="button" (not submit)
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var password = $("#Password").val();
var cpassword = $("#cpassword").val();
var gender = $("input[name=gender]:checked").val();
var dob = $("#dob").val();
var image = $("#image").val();
var status = $("#status").val();
var submit = $("#submit").val();
var dataString='fname='+fname+'&lname='+lname+'&email='+email+ '&password='+password+
'&cpassword='+cpassword+ '&gender='+gender+ '&dob='+dob+ '&image='+image+ '&status='+status+
'&submit'+submit;
if(fname=="" || lname=="" || email==""){
alert("please fill the fields");
}else if(fname.length < 5 || fname.length > 20){
alert("user name must be between 5 to 20 characters");
}else if(password.length < 5 || password.length > 8){
alert("password must be between 5 to 8 characters");
}else if(!gender){
alert("please select your gender");
}else if(!dob){
alert("please select your birth day");
}else{
$.ajax({
type:"POST",
url:"create-user.php",
data:dataString,
cache:false,
success:function(result){
alert(result);
}
});//ajax closed
}
return false;
});
});
</script>
<div id="content" class="col-lg-10 col-sm-10">
<!-- content starts -->
<div>
<ul class="breadcrumb">
<li>
Home
</li>
<li>
Forms
</li>
</ul>
</div>
<div class="box-content">
<div id="userRegis">
<div class="form-group">
<label for="exampleInputEmail1">First Name</label>
<input class="form-control" id="fname" placeholder="Enter First Name" type="text" name="fname">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last Name</label>
<input class="form-control" id="lname" placeholder="Enter Last Name" type="text">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input class="form-control" id="email" placeholder="Enter Email" type="text">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Password</label>
<input class="form-control" id="Password" placeholder="Enter Password" type="password">
</div>
<div class="form-group">
<label for="exampleInputEmail1">confirm Password</label>
<input class="form-control" id="cPassword" placeholder="Enter confirm Password" type="password" name="cpassword">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Gender</label>
<div class="radio">
<label>
<input type="radio" name="gender" id="gender" value="MALE">Male
</label>
<label>
<input type="radio" name="gender" id="gender" value="FEMALE">Female
</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">date of birth</label>
<input class="form-control" id="dob" placeholder="Enter Password" type="date" name="dob">
</div>
<div class="form-group">
<label for="exampleInputEmail1">image</label>
<input class="form-control" id="image" placeholder="Enter Password" type="file" name="image">
</div>
<div class="form-group">
<div class="control-group">
<label class="control-label" for="selectError">Status</label>
<div class="controls">
<select id="status" data-rel="chosen" name="status">
<option value="0">SELECT</option>
<option value="1">ACTIVE</option>
<option value="2">PENDING</option>
</select>
</div>
</div>
<br>
<input type="submit" name="submit" id="submit" value="create user" class="btn btn-default">
</div>
</div>
</div>
</div>

Categories

Resources