Validate form fields and remove error using jQuery - javascript

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>

Related

Javascript, validation of password with bootstrap

i'm trying to learn Javascript and some basic HTML with bootstrap v5.
I created a Sign-in form and now i'm try to do some validation for the required field.
I follow the Bootstrap documentations and i managed to get validation for all my input field except for the password, i want to verify if the password are the same or if they are empty field...but i'm stuck.. not familiar with javascript.
my attempt in javascript:
let forms = document.querySelectorAll(".needs-validations");
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
Array.prototype.slice.call(forms).forEach( function (form){
form.addEventListener("submit",function (ev) {
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.className = 'form-control is-invalid'
pass2.className = 'form-control is-invalid'
}
if (!form.checkValidity()){
ev.preventDefault()
ev.stopPropagation()
}
form.classList.add("was-validated")
})
})
but here the result:
As you can see password is always valid and i don't understand why.
my html:
<body class="body">
<div class="center">
<h4 class="title">Sign Up New User</h4>
<form name="signin-form" method="post" class="needs-validations" novalidate id="forms">
<div class="container">
<div class="row mt-3">
<div class="col">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required>
<div class="invalid-feedback">
Name can't be empty
</div>
</div>
<div class="col">
<label for="surname" class="form-label">Surname</label>
<input type="text" class="form-control" id="surname" placeholder="Surname" required>
<div class="invalid-feedback">
Surname can't be empty
</div>
</div>
</div>
<div class="row mt-3">
<div class="col">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required>
<div class="invalid-feedback">
invalid email
</div>
</div>
<div class="col-4 text-end">
<label for="email" class="form-label">Role</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>Captain</option>
<option>First Officer</option>
</select>
<div class="invalid-feedback">
Please select role
</div>
</div>
</div>
<div class="row mt-3 ">
<div class="col">
<label for="password1" class="form-label ">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
</div>
<div class="col">
<label for="password2" class="form-label ">Confirm Password</label>
<input type="password" class="form-control" id="password2" placeholder="Password">
<div class="invalid-feedback">
Password not match
</div>
</div>
</div>
<div class="row-cols-2 mt-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</div>
<script src="/validation.js"></script>
<script src="/js/bootstrap.bundle.min.js" ></script>
</body>
What I don't understand is, that your password fields seem to be having a valid class in your posted screenshot. But I can't find it anywhere in your code (neither HTML nor JS).
I'd do it like this:
(Note: I didn't test this code, but it should work. If it works and you want to learn from it, I recommend to read through it step by step and apply it to your logic instead of just copy pasta.)
let form = document.querySelector("form.needs-validations");
// or, to be more specific:
// let form = document.querySelector("form[name='signing-form']")
form.addEventListener("submit",function (ev) {
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.classList.add('is-invalid');
pass2.classList.add('is-invalid');
}
if (!form.checkValidity()){
ev.preventDefault();
ev.stopPropagation();
}
form.classList.add("was-validated");
})
Note: the functionality to validate the content of your password-fields will only be triggered once you hit the submit button.

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();

How to send localstorage with form

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>

disable an input if another input is clicked

I have three sections in a form, the first one contains one input and the second contains three inputs and the third contains a checkbox. How to
disable the two sections if checkbox is checked
disable the checkbox and a section if I tapped a text in the other section
enable the three sections if all of them are empty
I must have only one active section everytime.
What I did is not the solution because there is a problem in the second section. if only one input is empty in this section all the other inputs are enabled. any one can help me please.
Thanks and sorry about my english
document.getElementById("client").onblur = function () {
if (this.value.length > 0) {
document.getElementById("FirstName").disabled=true;
document.getElementById("LastName").disabled=true;
document.getElementById("Email").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("FirstName").disabled=false;
document.getElementById("LastName").disabled=false;
document.getElementById("Email").disabled=false;
document.getElementById("standard").disabled=false;
}
}
document.getElementById("FirstName").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("LastName").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("Email").onblur = function () {
if (this.value.length > 0) {
document.getElementById("client").disabled=true;
document.getElementById("standard").disabled=true;
}else {
document.getElementById("client").disabled = false;
document.getElementById("standard").disabled = false;
}
}
document.getElementById("standard").onblur = function () {
if (this.checked) {
document.getElementById("client").disabled=true;
document.getElementById("FirstName").disabled=true;
document.getElementById("LastName").disabled=true;
document.getElementById("Email").disabled=true;
}else {
document.getElementById("client").disabled=false;
document.getElementById("FirstName").disabled=false;
document.getElementById("LastName").disabled=false;
document.getElementById("Email").disabled=false;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-md-4">
<div class="row">
<div class="form-group col-md-12">
<label>Search Client</label>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<div class="input-group custom-search-form margin-bottom">
<input id="client" name="client" type="text" class="form-control input-sm" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default btn-sm" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-8">
<div class="row">
<div class="form-group col-md-12">
<label>New Client</label>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<input type="text" class="form-control input-sm" id="FirstName" placeholder="First Name">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control input-sm" id="LastName" placeholder="Last Name">
</div>
<div class="form-group col-md-4">
<input type="email" class="form-control input-sm" id="Email" placeholder="Email">
</div>
</div>
</div>
</div>
<div class="checkbox margin-bottom">
<label>
<input id="standard" type="checkbox" value="">Standard
</label>
</div>
It sounds like you may want try the focus listener instead of the on Blur listener.
https://developer.mozilla.org/en-US/docs/Web/Events/focus
The second element seems to work when I entered in values for all of the fields. It looks like it's checking the length of what was entered.

Form Validation with jQuery - Weird Redirect

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
}

Categories

Resources