Alright, so I'm trying to do form validation with jQuery. Not sure why but when you click submit it redirects you to the page you're at already.
The forms action is blank and I included the javascript file in the header.
I will put the code below. Let me know if you see whats wrong. I want it to validate with jQuery then send you to a php file with those values in the method POST.
Register.js:
$(document).ready(function() {
$('button[name=regsubmit]').click(function(){
var fname = $('input[name=regfirstname');
var lname = $('input[name=reglastnaame');
var email = $('input[name=regemail');
var password = $('input[name=regpassword');
var repeatpassword = $('input[name=regrepeatpassword');
var username = $('input[name=regusername');
var atpos = email.indexOf("#");
var dotpos = email.indexOf(".");
if (fname==null || fname=="")
{
alert('First name must be filled out!');
return false;
}
if (lname==null || lname=="")
{
alert('Last name must be filled out!');
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert('Not a valid e-mail address!');
return false;
}
if (username==null || username=="")
{
alert("Username field must be filled out!");
return false;
}
if (password==null || password=="")
{
alert("Subject field must be filled out!");
return false;
}
if (repeatpassword==null || repeatpassword=="")
{
alert("Repeat password field must be filled out!");
return false;
}
if (password != repeatpassword)
{
alert("The passwords do not match!");
return false;
}
else
{
location.href="register.php";
}
});
});
Form:
<form name="register" method="POST">
<fieldset>
<div class="form-container row-fluid">
<div class="span6">
<div class="control-group">
<label class="control-label" for="regfirstname">First Name</label>
<div class="controls">
<input id="regfirstname" tabindex="1" name="regfirstname" type="text" placeholder="First Name" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regusername">Username</label>
<div class="controls">
<input id="regusername" tabindex="3" name="regusername" type="text" placeholder="Username" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regpassword">Password</label>
<div class="controls">
<input id="regpassword" tabindex="5" name="regpassword" type="password" placeholder="Password" class="input-large">
</div>
</div>
<div class="controls">
<button id="regsubmit" tabindex="7" name="regsubmit" class="button background-asbestos">Submit</button>
</div>
</div><!-- .span6 -->
<div class="span6">
<div class="control-group">
<label class="control-label" for="reglastname">Lastname</label>
<div class="controls">
<input id="reglastname" tabindex="2" name="reglastname" type="text" placeholder="Lastname" class="input-large" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regemail">Email</label>
<div class="controls">
<input id="regemail" name="regemail" tabindex="4" type="text" placeholder="example#example.com" class="input-large"</td>
</div>
</div>
<div class="control-group">
<label class="control-label" for="regrepeatpassword">Repeat Password</label>
<div class="controls">
<input id="regrepeatpassword" tabindex="6" name="regrepeatpassword" type="password" placeholder="Repeat Password" class="input-large" required>
</div>
</div>
<!-- .span6 -->
<!-- span6 -->
</div><!-- .row-fluid -->
</fieldset>
</form>
Alright your JS and HTML is a big mess of stuff, so I won't recreate it all, but basics:
Give your form an ID:
<form id="SomeForm" name="register" method="POST">
Then prevent default action, and submit if passes:
// reference the button by the ID you gave it
$('#regsubmit').click(function(e){
// stop original submission
e.preventDefault();
// all your checking stuff here, but if true, then:
document.getElementById('SomeForm').submit();
});
This ensures that you are referencing the button correctly, preventing submission correctly, and submitting only if valid.
prevent default action on submit
$('button[name=regsubmit]').click(function(e)
{
e.preventDefault();
//your code below
}
Related
Hello I am trying to validate form using jQuery but I am getting some errors, one first when there is an error it will show an error in small tag on button click, which is all ok but when I try to re validate on button click rather then removing errors tags then reprints it adds another error tag next to each other, I tried several ways but nothing works for me.
In last I want to do if no error exist then prints a message, as I am new to jQuery, so i used the method from which I can handle it, but if any expert have better suggestion in my code for rewriting I will defiantly consider it
My HTML
<form class="form-horizontal" id="mainForm" name="mainForm">
<!-- Fields Top -->
<div class="custom_nic_fields">
<!-- Name Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtYourName">Your Name</label>
<input type="text" class="form-control" id="txtYourName" placeholder="Jhon Smith" name="txtYourName" required>
</div>
</div>
<!-- Email Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtEmail">Your Email(required)</label>
<input type="email" class="form-control" id="txtEmail" placeholder="you#example.com" name="txtEmail" required>
</div>
</div>
<!-- Phone Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtPhone">Contact Phone No.</label>
<input type="text" class="form-control" id="txtPhone" placeholder="+10000000000" name="txtPhone" required>
</div>
</div>
<!-- Address Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtAddress">Address</label>
<input type="text" class="form-control" id="txtAddress" placeholder="Aparatment, Building, City" name="txtAddress">
</div>
</div>
<!-- State Zip Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtStateZip">State, Zip</label>
<input type="text" class="form-control" id="txtStateZip" placeholder="Texas 78240" name="txtStateZip">
</div>
</div>
<button type="button" id="custombtnform" class="btn btn-primary custombtnform">Send</button>
</div>
<!-- Fields End -->
</form>
My JS Part
jQuery(document).ready(function($) {
$("#custombtnform").click(function(e) {
e.preventDefault();
var errors = [];
$("#custombtnform").siblings('.errors_show').remove();
//Validate Name
var txtName = $("#txtYourName").val();
if (!txtName.match(/^[a-zA-Z\s-]+$/)) {
$("#txtYourName").addClass("error_field");
$('#txtYourName').after('<small class="errors_show">A valid name is requred</small>');
return false;
} else {
$("#txtYourName").removeClass("error_field");
}
//Validate Email
var txtEmail = $("#txtEmail").val();
if (!txtEmail.match(/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
$("#txtEmail").addClass("error_field");
$('#txtEmail').after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>');
return false;
} else {
$("#txtEmail").removeClass("error_field");
$("#txtEmail").siblings('small.errors_show').remove();
}
//Validate Phone
var txtPhone = $("#txtPhone").val();
if (!txtPhone.match(/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g)) {
$("#txtPhone").addClass("error_field");
$('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>');
return false;
} else {
$("#txtPhone").removeClass("error_field");
$("#txtPhone").siblings('small.errors_show').remove();
}
if ($('small.errors_show').length == 0) {
console.log("No errors found");
}
});
});
You can use $("#mainForm .errors_show").remove(); $("#mainForm .error_field").removeClass('error_field'); in start of click event, for clear error state. Your code will be much shorter:
jQuery(document).ready(function($) {
$("#custombtnform").click(function(e) {
e.preventDefault();
$("#mainForm .errors_show").remove();
$("#mainForm .error_field").removeClass('error_field');
//Validate Name
var txtName = $("#txtYourName").val();
if (!txtName.match(/^[a-zA-Z\s-]+$/)) {
$("#txtYourName").addClass("error_field");
$('#txtYourName').after('<small class="errors_show">A valid name is requred</small>');
}
//Validate Email
var txtEmail = $("#txtEmail").val();
if (!txtEmail.match(/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
$("#txtEmail").addClass("error_field");
$('#txtEmail').after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>');
}
//Validate Phone
var txtPhone = $("#txtPhone").val();
if (!txtPhone.match(/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g)) {
$("#txtPhone").addClass("error_field");
$('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>');
}
if ($('#mainForm .errors_show').length == 0) {
console.log("No errors found");
}
});
});
See in playground https://jsfiddle.net/denisstukalov/a6wnx89j/5/#&togetherjs=x0DBljsUxA
after() places an element just after the selected event. So we need to remove it before every validation
jQuery(document).ready(function($) {
$("#custombtnform").click(function(e) {
e.preventDefault();
var errors = [];
//removing all error messages from mainForm
$("#mainForm .errors_show").remove();
//Validate Name
var txtName = $("#txtYourName").val();
if (!txtName.match(/^[a-zA-Z\s-]+$/)) {
$("#txtYourName").addClass("error_field");
$('#txtYourName').after('<small class="errors_show">A valid name is requred</small>');
return false;
} else {
$("#txtYourName").removeClass("error_field");
}
//Validate Email
var txtEmail = $("#txtEmail").val();
if (!txtEmail.match(/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
$("#txtEmail").addClass("error_field");
$('#txtEmail').after('<small class="errors_show">A valid email address is requred</smaladdress is requred</small>');
return false;
} else {
$("#txtEmail").removeClass("error_field");
}
//Validate Phone
var txtPhone = $("#txtPhone").val();
if (!txtPhone.match(/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g)) {
$("#txtPhone").addClass("error_field");
$('#txtPhone').after('<small class="errors_show">A valid phone is requred</small>');
return false;
} else {
$("#txtPhone").removeClass("error_field");
}
if ($('small.errors_show').length == 0) {
console.log("No errors found");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal" id="mainForm" name="mainForm">
<!-- Fields Top -->
<div class="custom_nic_fields">
<!-- Name Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtYourName">Your Name</label>
<input type="text" class="form-control" id="txtYourName" placeholder="Jhon Smith" name="txtYourName" required>
</div>
</div>
<!-- Email Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtEmail">Your Email(required)</label>
<input type="email" class="form-control" id="txtEmail" placeholder="you#example.com" name="txtEmail" required>
</div>
</div>
<!-- Phone Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtPhone">Contact Phone No.</label>
<input type="text" class="form-control" id="txtPhone" placeholder="+10000000000" name="txtPhone" required>
</div>
</div>
<!-- Address Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtAddress">Address</label>
<input type="text" class="form-control" id="txtAddress" placeholder="Aparatment, Building, City" name="txtAddress">
</div>
</div>
<!-- State Zip Field -->
<div class="col-xs-12 col-md-12">
<div class="form-group">
<label for="txtStateZip">State, Zip</label>
<input type="text" class="form-control" id="txtStateZip" placeholder="Texas 78240" name="txtStateZip">
</div>
</div>
<button type="button" id="custombtnform" class="btn btn-primary custombtnform">Send</button>
</div>
<!-- Fields End -->
</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();
I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>
I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>
I don't know what's wrong in this. Validation not working here.
Form submitted without validation.
function validate()
{
if( document.myForm.username.value == "" )
{
alert( "Please provide your user name!" );
document.myForm.fname.focus() ;
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.myform.email.value))
{
alert("You have entered an invalid email address!")
return false;
}
}
return false;
}
<form class="form-horizontal" method="post" id="myForm" action=" " name="myForm" onsubmit="return validate()">
<div class="form-group">
<p class="text-center">Register Information</p>
<br>
</div>
<div class="form-group">
<label for="username" class="control-label col-xs-2">UserName</label>
<div class="col-xs-2">
<input type="text" class="form-control" id="name" name="username"
placeholder="UserName">
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-xs-2">Email Address</label>
<div class="col-xs-2">
<input type="text" class="form-control" name="email" id="email"
placeholder="abc#domain.com" />
</div>
</div>
<div class="form-group">
<label for="password" class="control-label col-xs-2">Password</label>
<div class="col-xs-2">
<input type="password" class="form-control" name="password" id="password"
placeholder="##########" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button type="submit" name="submit" class="btn btn-primary">submit</button>
</div>
</div>
</form>
I don't know whats wrong in this.Please help me to fix it.
Try using type="email" form email id field validation and 'required' directive for required fields.
<input type="email" class="form-control" name="email" id="email" placeholder="abc#domain.com" required/>
If you tried to do validation using HTML5 features you have to add attrributes like required or pattern to your inputs.
You trigger validate() on submit bu there is no javascript code in the markup you pasted.
Start with this article.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation
It describes native browser support for valdiation and later suggests some libraries and examples of custom code.
In validate function the closing bracket just before the last "return false" statement is unnecessary.