I have a form that deals with registration like below:
I want to validate each tab instead of the entire form so user have to fill up first tab before moving to the next. I tried using validator.element( "email" ) but it does not respond at all.
This is my code:
<form method="POST" action="{{ route('register') }}" id="register-form">
#csrf
<div class="tab-content" id="myTabContent">
<!-- Registration Tab-->
<div class="tab-pane fade show active" id="registration" role="tabpanel" aria-labelledby="registration-tab">
<h5 class="text-center" style="background-color: #303030; color: #ffffff; padding: .5rem; border: 1px solid #e5e5e5;">Account Particulars</h5>
<div class="form-row">
<div class="form-group col-md-12">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" required id="email" placeholder="Email">
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" required id="password">
</div>
<div class="form-group col-md-12">
<label for="password-confirm">Confirm Password</label>
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<!-- Next Button -->
<div class="text-right">
<!-- <a class="btn btn-secondary next-button" id="information-tab" data-toggle="tab" href="#information" role="tab" aria-controls="profile" aria-selected="false">Next</a> -->
<a class="btn btn-secondary next-button bjsh-btn-gradient" id="next-btn">Next</a>
</div>
</div>
<!-- Information Tab -->
<div class="tab-pane fade" id="information" role="tabpanel" aria-labelledby="information-tab">
<!-- Personal Particulars -->
<h5 class="text-center" style="background-color: #303030; color: #ffffff; padding: .5rem; border: 1px solid #e5e5e5;">Personal Particulars</h5>
<div class="form-row">
<div class="form-group col-md-6">
<label for="full_name">Full Name (as per NRIC)</label>
<input type="text" name="full_name" class="form-control" id="full_name" required placeholder="Full Name">
</div>
<div class="form-group col-md-6">
<label for="nric">NRIC Number</label>
<input type="text" name="nric" class="form-control" id="nric" placeholder="NRIC Number">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="address_1">Address Line 1</label>
<input type="text" name="address_1" id="address_1" class="form-control" placeholder="Residential Address Line 1">
</div>
<div class="form-group col-md-12">
<label for="address_1">Address Line 2</label>
<input type="text" name="address_2" id="address_2" class="form-control" placeholder="Residential Address Line 1">
</div>
<div class="form-group col-md-12">
<label for="address_1">Address Line 3</label>
<input type="text" name="address_3" id="address_3" class="form-control" placeholder="Residential Address Line 1">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" class="form-control" placeholder="Postcode">
</div>
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" name="city" id="city" class="form-control" placeholder="City">
</div>
<div class="form-group col-md-12">
<label for="state">State</label>
<select name="state" id="state" class="form-control">
<option disabled selected>Choose your state..</option>
#foreach($states as $state)
<option class="text-capitalize" value="{{ $state->id }}">{{ $state->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="contact_number_home">Contact Number (Home)</label>
<input type="text" name="contact_number_home" class="form-control" placeholder="Home Contact Number">
</div>
<div class="form-group col-md-6">
<label for="contact_number_mobile">Contact Number (Mobile)</label>
<input type="text" name="contact_number_mobile" class="form-control" placeholder="Mobile Contact Number">
</div>
</div>
Script (broken):
var validator = $( "#register-form" ).validate({
rules: {
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 8,
},
password_confirmation:{
required: true,
minlength: 8,
equalTo: "#password"
}
},
messages: {
email: "Please enter an email",
password: "Please enter a password",
password_confirmation: "Password does not match"
}
});
$('#next-btn').click(function() {
var validator = $( "#myform" ).validate();
validator.element("email");
});
How do I make it work considering I need to validate each tab before the final tab which has a submit button?
I used a bootstrap 4 css styling for the example code, this can easily be changed by adding your own css to the JQuery class functions.
I used a toggling of attributes and classes as well as a msg field to display error and success messages for the example. Specifically I am disabling the input fields proceeding the focused input until one has been finished the proceeding fields lock. Once the match on the passwords is complete the submit button unlocks.
UPDATE March 22nd 2020:
Added minimum requirement for password.
You can also add required characters to the password section as well, just add a regex with matching characters in the password and password confirm sections of the JQuery code.
IMPORTANT NOTE: Front end validation should only be done for formatting really, the bulk of your validation should be done on the backend!
$("#confirm_password").keyup(function() {
var passLength = $(this).val().length;
var minLength = 8;
if (passLength < minLength) {
$("#msg").html('Length is short, password must be a minumum of ' + minLength + ' characters.').removeClass("alert-success").addClass("alert alert-danger");
$("#submit").prop('disabled', true);
} else if ($("#password").val() != $(this).val()) {
$("#msg").html("Password do not match").removeClass("alert-success").addClass("alert alert-danger");
$("#submit").prop('disabled', true);
} else {
$("#msg").html("Passwords matched, you can submit the form now").removeClass("alert-danger").addClass("alert alert-success");
$("#submit").prop('disabled', false);
}
});
$("#password").keyup(function() {
var passLength = $(this).val().length;
var minLength = 8;
if (passLength < minLength) {
$("#msg").html('Length is short, password must be a minumum of ' + minLength + ' characters.').removeClass("alert-success").addClass("alert alert-danger");
$("#submit").prop('disabled', true);
} else if ($(this).val() != $("#confirm_password").val()) {
$("#msg").html("Password do not match").removeClass("alert-success").addClass("alert alert-danger");
$("#submit").prop('disabled', true);
} else {
$("#msg").html("Passwords matched").removeClass("alert-danger").addClass("alert alert-success");
$("#submit").prop('disabled', false);
}
});
$("#usr_email").change(function() {
var sEmail = $(this).val();
if ($.trim(sEmail).length == 0) {
$("#msg").html("Email is mandatory").removeClass("alert-success").addClass("alert alert-danger");
$("#password").prop('disabled', true);
$("#confirm_password").prop('disabled', true);
$("#submit").prop('disabled', true);
} else if (validateEmail(sEmail)) {
$("#msg").html("Your Email is valid, now you can continue").removeClass("alert-danger").addClass("alert alert-success");
$("#password").prop('disabled', false);
$("#confirm_password").prop('disabled', false);
$("#submit").prop('disabled', true);
} else {
$("#msg").html("Invalid Email address").removeClass("alert-success").addClass("alert alert-danger");
$("#password").prop('disabled', true);
$("#confirm_password").prop('disabled', true);
$("#submit").prop('disabled', true);
}
});
// Function that validates email address through a regular expression.
function validateEmail(sEmail) {
var filter = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (filter.test(sEmail)) {
return true;
} else {
return false;
}
}
<!-- Bootstrap 4-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<form method="post">
<label for="usr_email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input class="form-control" type="email" id="usr_email" name="usr_email" placeholder="EMAIL" required>
</div>
<label for="usr_password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input class="form-control" id="password" type="password" name="usr_password" placeholder="PASSWORD" required>
</div>
<label for="confirm_password" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
<input class="form-control" id="confirm_password" type="password" name="confirm_password" placeholder="CONFIRM PASSWORD" required>
</div>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<div class="col-sm-6" id="msg"></div>
Related
Hello i need some help i sure this topic have been answer before but i try use some of the reference from how to check confirm password field in form without reloading page
I woud like that the password and confirm password will display the error if password do not match without have to click on submit button or reloading page i have my code below where it don't work, i would like for some help as how i can display it of course i not using just a normal form i am using
<form class="needs-validation" novalidate>
This is my code below
function onChange() {
const password = document.querySelector('input[name=validationpassword]');
const confirm = document.querySelector('input[name=validationconfirmpassword]');
if (confirm.value === password.value) {
confirm.setCustomValidity('');
} else {
confirm.setCustomValidity('Passwords do not match');
}
}
<form class="needs-validation" novalidate>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">*Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<!--<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div> -->
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">*Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
</div>
</div>
</form>
You have to use onkeyup() event for check conform password.
Here down is example:
function myFunction() {
var password = document.querySelector('input[name=validationpassword]').value;
var confirm = document.querySelector('input[name=validationconfirmpassword]').value;
var matchedOrNot = (confirm == password) ? "Password matched" : "Password not matched";
var color = (matchedOrNot == "Password matched") ? "green" : "red";
document.getElementById("toggleconfirmPassword").className = color;
document.getElementById("toggleconfirmPassword").innerHTML = matchedOrNot;
}
.red
{
margin-top: 5px;
color: red;
font-weight: bold;
}
.green
{
margin-top: 5px;
color: green;
font-weight: bold;
}
<form class="needs-validation" novalidate>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">*Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" required>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">*Re-enter Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onkeyup="myFunction()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<br>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
</div>
</div>
</form>
You can use onkeyup to check the passwords with every key press.
So instead of onChange even use this:
onkeyup ="onChange()"
function onChange() {
const password = document.querySelector('input[name=validationpassword]');
const confirm = document.querySelector('input[name=validationconfirmpassword]');
console.log(confirm.value === password.value)
if (confirm.value === password.value) {
confirm.setCustomValidity('');
} else {
confirm.setCustomValidity('Passwords do not match');
}
}
<form class="needs-validation" novalidate>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">*Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<!--<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div> -->
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">*Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onkeyup ="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
</div>
</div>
</form>
It is generally not a good idea to use inline event handlers (<div onclick="...">.
Here is a minimal reproducable example. It uses a handler for the keyup and focusin events comparing both values and messages the user about the result. The handling is set for both password fields.
$(`#confirm_password, #passwords`).on({
keyup: handleConfirmation,
focusin: handleConfirmation} );
function handleConfirmation() {
const pass = $(`#passwords`).val();
const compare = $(`#confirm_password`).val();
// one of the fields is empty, remove message
if (!pass.trim() || !compare.trim()) {
return $(`#toggleconfirmPassword`).html(``)
}
// otherwise, compare and display result
const isOk = pass === compare;
$(`#toggleconfirmPassword`).html(isOk ? ` OK ` : `Passwords are not equal (yet)`);
}
body {
margin: 2rem;
font: normal 12px/15px verdana, arial;
}
#toggleconfirmPassword {
color: red;
font-weight: bold;
}
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="validationpassword" class="col-form-label passwordadduser">
*Password:
</label>
<input name="validationpassword" type="password" id="passwords"
placeholder="Password" required>
<div>
<label for="validationconfirmpassword">
*Re-enter password:
</label>
<input name="validationconfirmpassword" type="password"
id="confirm_password" placeholder="Confirm Password" required>
<i id="toggleconfirmPassword"></i>
</div>
I have a problem which I dont seem to find a solution for. The problem is this: I have some jQuery which will keep the button disabled until all the form's fields are filled up. When all the fields are filled up the button is being enabled, but the javascript onSubmit event used for the google recaptcha is not being trigerred. Anyone can help in this, please
Code is the one below:
//jquery to disable button until all fields are filled up
$().ready(function() {
// validate signup form on keyup and submit
$("#fbForm").validate({
rules: {
name: {
required: true
},
surname: {
required: true
},
terms: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#fbForm').change(function() {
if ($("#fbForm").valid()) {
$("#btnSubmit").removeAttr("disabled");
}
});
//recaptcha JS
function onSubmit(token) {
if (screen.width >= 768) {
document.getElementById("fbForm").submit();
}else if (screen.width <= 767){
document.getElementById("fbForm2").submit();
}
}
<form id="fbForm"class="well form-horizontal" action="winesOfDistinction.php?send=true" method="post" data-toggle="validator">
<div class="form-group">
<label for="name "class="col-md-4 control-label">First Name</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="First Name" name="name" id="name" class="form-control" data-minlength="2" data-error="Minimum Lenght of First Name must be made up of at least 2 characters!" value="<?= $name ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<!-- Surname: Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="surname">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Last Name" name="surname" id="surname" class="form-control" data-minlength="2" data-error="Minimum Lenght of Last Name must be made up of at least 2 characters!" value="<?= $surname ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group text-center">
<div class="checkbox">
<label>
<input type="checkbox" name="terms"id="terms" data-error="Please check the GDPR Disclaimercheck box in order to be able to submit the data" required>
I agree
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4"><br>
<button id="btnSubmit" name="btnSubmit" disabled="disabled" type="submit" value="" class="g-recaptcha btn btn-success" data-sitekey="6LfuAWcUAAAAAEKjLeOZfygAMxAeld1k4UUMGnfN" data-callback='onSubmit'>SUBMIT <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
You are missing a } at the last line to close the ready function. Fix that first.
$().ready(function() {
$('#num').validate();
// validate signup form on keyup and submit
$("fbForm").validate({
rules: {
name: {
required: true
},
surname: {
required: true
},
terms: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#fbForm').change(function() {
if ($("#fbForm").valid()) {
$("#btnSubmit").removeAttr("disabled");
}
});
//recaptcha JS
function onSubmit(token) {
if (screen.width >= 768) {
document.getElementById("fbForm").submit();
}else if (screen.width <= 767){
document.getElementById("fbForm2").submit();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<form name="formSend" id="fbForm" class="well form-horizontal" action="winesOfDistinction.php?send=true" method="post" data-toggle="validator">
<fieldset>
<div class="form-group">
<label for="name "class="col-md-4 control-label">First Name</label>
<div class="col-md-4">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="First Name" name="name" id="name" class="form-control" data-minlength="2" data-error="Minimum Lenght of First Name must be made up of at least 2 characters!" value="<?= $name ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<!-- Surname: Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="surname">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" placeholder="Last Name" name="surname" id="surname" class="form-control" data-minlength="2" data-error="Minimum Lenght of Last Name must be made up of at least 2 characters!" value="<?= $surname ;?>" required>
</div>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group text-center">
<div class="checkbox">
<label>
<input type="checkbox" name="terms"id="terms" data-error="Please check the GDPR Disclaimercheck box in order to be able to submit the data" required>
I agree
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-4"><br>
<button id="btnSubmit" name="btnSubmit" disabled="disabled" type="submit" value="" class="g-recaptcha btn btn-success" data-sitekey="6LfuAWcUAAAAAEKjLeOZfygAMxAeld1k4UUMGnfN" data-callback='onSubmit'>SUBMIT <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</fieldset>
</form>
Okay, Missing jquery validtor and syntax errors were causing the problem. The snippet works fine.You should use visual code as editor and please resolve syntax errors before posting here.
So I am making a web based application that needs to have the ability for an admin user to create sub users. I have the sql database working correctly when I create a user but the issue is that when I go ahead and add a user, it redirects me to a different php page. With the javascript running, it normally just says successful when I change password or change username. Here's the code.
<!-- create username -->
<form action="php_action/createUsername.php" method="post" class="form-horizontal" id="createUsernameForm">
<fieldset>
<legend>Create Username</legend>
<div class="createUsenrameMessages"></div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label">New User</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="usernameC" name="usernameC" placeholder="username" value="<?php echo $result['username']; ?>"/>
</div>
</div>
<div class="changePasswordMessages"></div>
<div class="form-group">
<label for="npassword" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="npasswordC" name="npasswordC" placeholder="New Password">
</div>
</div>
<div class="form-group">
<label for="cpassword" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="cpasswordC" name="cpasswordC" placeholder="Confirm Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="user_id" id="user_id" value="<?php echo $result['user_id'] ?>" />
<button type="submit" class="btn btn-success" data-loading-text="Loading..." id="createUsernameBtn"> <i class="glyphicon glyphicon-ok-sign"></i> Add User </button>
</div>
</div>
</fieldset>
</form>
here is the script
// create username
$("#createUsernameForm").unbind('submit').bind('submit', function() {
var form = $(this);
var username = $("#usernameC").val();
var newPassword = $("#npasswordC").val();
var conformPasswordPassword = $("#cpasswordC").val();
if(newPassword == "" || conformPassword == "") {
if(newPassword == "") {
$("#npasswordC").after('<p class="text-danger">The Current Password field is required</p>');
$("#npasswordC").closest('.form-group').addClass('has-error');
} else {
$("#npasswordC").closest('.form-group').removeClass('has-error');
$(".text-danger").remove();
}
if(conformPassword == "") {
$("#cpassword").after('<p class="text-danger">The Conform Password field is required</p>');
$("#cpassword").closest('.form-group').addClass('has-error');
} else {
$("#cpassword").closest('.form-group').removeClass('has-error');
$(".text-danger").remove();
}
return false;
});
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 am having an issue using jQuery validate against a form in a current project.
I am sure it is a typo I am missing or something small, but can't sem to figure out why it is occurring.
The error I am getting in the console debugger is: Object doesn't support property or method 'validate'
The bundle configuration file:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/ContactForm.js"));
The code snippets are below:
<form action="#Url.Action("UpdateContactInformation", "ContactController")" method="post" role="form" class="form-horizontal" id="contactForm">
<input type='hidden' name='csrfmiddlewaretoken' value='brGfMU16YyyG2QEcpLqhb3Zh8AvkYkJt' />
<!-- First Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">First Name</label>
<div class="col-md-4">
<input class="form-control" id="id_firstName" maxlength="75" name="txtFirstName" placeholder="First Name" required="required" title="" type="text" />
</div>
</div>
<!-- Last Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Last Name</label>
<div class="col-md-4">
<input class="form-control" id="id_lastName" maxlength="75" name="txtlastName" placeholder="Last Name" required="required" title="" type="text" />
</div>
</div>
<!-- Title Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Title</label>
<div class="col-md-4">
<input class="form-control" id="id_title" maxlength="75" name="txtTitle" placeholder="Title" required="required" title="" type="text" />
</div>
</div>
<!-- Address Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Address</label>
<div class="col-md-4">
<input class="form-control" id="id_address" maxlength="75" name="txtAddress" placeholder="Address" required="required" title="" type="text" />
</div>
</div>
<!-- City Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">City</label>
<div class="col-md-4">
<input class="form-control" id="id_city" maxlength="75" name="txtCity" placeholder="City" required="required" title="" type="text" />
</div>
</div>
<!-- State Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">State</label>
<div class="col-md-4">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuStates" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Select State
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="statesDropDownMenu" aria-labelledby="dropdownMenuStates">
</ul>
</div>
</div>
</div>
<!-- Zip Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">ZipCode</label>
<div class="col-md-4">
<input class="form-control" id="id_zipCode" maxlength="75" name="txtZipCode" placeholder="ZipCode" required="required" title="" type="number" />
</div>
</div>
<!-- Email Primary Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Email Primary</label>
<div class="col-md-4">
<input class="form-control customEmail" id="id_emailPrimary" maxlength="75" name="txtEmailPrimay" placeholder="Email Primary" required="required" />
</div>
</div>
<!-- Email Secondary (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailSecond" maxlength="75" name="txtEmailSecond" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<!-- Email Third (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailThird" maxlength="75" name="txtEmailThird" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-user"></span> Submit Contact Info
</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval");
#Scripts.Render("~/bundles/custom"); //contains the file I am trying to add $.validate.AddMethod() to
Here is the code for Contact.js
$.validator.addMethod(
"customEmail",
function (value, element) {
var re = new RegExp("/^#{0,2}\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*#{0,2}$/");
return this.optional(element) || re.test(value);
},
"Please enter a valid email address."
);
$(document).ready(function () {
console.log("Were here.........");
// populateStatesDropDown();
$('#contactForm').validate({ // initialize the plugin
rules: {
txtZipCode: {
required: true,
numeric: true
},
txtEmailPrimay: {
required: true,
customEmail:true
},
txtEmailSecond:{
required:false,
customEmail:true,
},
txtEmailThird: {
required: false,
customEmail:true
}
}
});
populateStatesList();
});
function populateStatesList() {
var url = "Contact/GetStates"; // Don't hard code your url's!
//$("#province_dll").change(function () {
var $statesDropDownMenu = $("#statesDropDownMenu"); // Use $(this) so you don't traverse the DOM again
var listItems = '';
$.getJSON(url, function (response) {
$statesDropDownMenu.empty(); // remove any existing options
console.log(response);
$.each(response, function (index, item) {
console.log("Now - " + item);
listItems += "<li>" + item + "</li>";
});
$statesDropDownMenu.html(listItems);
});
//});
}
You have an extra comma.
txtEmailSecond:{
required:false,
customEmail:true, // Here
},