I do have a jquery code to validate my form but unfornutately it is not that accurate. I would like to validate the fields thoroughly like only to accept numbers on phone field and only a valid email address on email field.
Also I would like to show the error ( or just add a red border one field ) as soon as the user types/inputs a value without clicking submit button, so it looks like a real time checker.
Can anyone derive my script, I am really not confident about this. Also derive my php code if u think it is wrong. Would love to learn how to use session also so user can only submit once every session.
Code:
<head>
<script>
$(function () {
$('.cbf').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
if ( name == "" ) {
alert('Please provide valid name');
$('#name').addClass('error');
}
else if ( phone == "" ) {
alert('Please provide a valid phone number');
$('#phone').addClass('error');
$('#name').removeClass('error');
}
else if ( email == "" ) {
alert('Please provide a valid email');
$('#email').addClass('error');
$('#phone').removeClass('error');
}
else {
$.ajax({
type: 'post',
url: 'index.php',
data: $('.cbf').serialize(),
data: "name="+ name +"& phone="+ phone +"& email="+ email,
success: function () {
alert('We will contact you shortly! Thanks!');
},
complete:function(){
$('.cbf').each(function(){
this.reset(); //Here form fields will be cleared.
});
}
});
$('#email').removeClass('error');
}
});
});
</script>
</head>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" class="cbf">
<fieldset>
<input type="text" id="name" name="name" value="" placeholder="Name">
<input type="text" id="phone" name="phone" value="" placeholder="Phone">
<input type="email" id="email" name="email" value="" placeholder="Email Address">
<input type="submit" id="submit" name="submit" value="Get Call Back">
</fieldset>
</form>
<?php
session_start();
if ('POST' === $_SERVER['REQUEST_METHOD']) {
$_SESSION['posted'] = true;
$to = "myemail#gmail.com";
$subject = "Someone wants a Call Back!";
// data the visitor provided
//$name_field = $_POST['name'];
//$phone_field = $_POST['phone'];
//$email_field = $_POST['email'];
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$phone = filter_var($_POST['phone'], FILTER_SANITIZE_INT);
//constructing the message
$body = " From: $name_field\n\n Phone: $phone_field\n\n E-mail: $email_field\n\n";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
Try this code :
$("#signupform").validate({
rules: {
email: {
required: true,
email: true
},
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
}
},
messages: {
email: {
required: "Please enter a valid email address.",
email: "Invalid Email Address."
},
mobile: {
required: "Please provide a mobile number.",
minlength: "Your mobile number must be 10 characters long.",
maxlength: "Your mobile number must be 10 characters long.",
number: "Please Enter number only."
}
}
});
Its better to validate on both server side and client side. Client side validate then display the error to user. On server side, you need to validate again, just because your JS code can be changed by malicious user.
A simple example with phone.
//client side
var phone = $('#phone').val();
//validate
if(/^\d+$/.test(phone) === false){ //not number
alert('Your phone number is not valid');
}
//on server side
$phone = $_POST['phone'];
if(is_numeric($phone)){
insert $phone into database.
}
Another way is to use HTML5 and new tags like : "email" and "tel" (tel is not supported for the moment) :
<input type="tel" name="phone" required>
and for email :
<input type="email" name="email" required>
Even the solution you choose, you have to do a control on the server side in Php for your case.
It's not the solution but in the futur, I think we should use these tags.
More informations : http://www.w3schools.com/html/html5_form_input_types.asp
Here is a simple jQuery validation:
The form:
<form id="myform">
email<input type="text" name="field1" />
<br/>
password<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
The validation part
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
http://jsfiddle.net/VuPPy/
Related
I'm pretty new to Javascript and PHP, but need to do a form validation for the user registration and I'm having trouble inserting the new user into the database.
I validate the form on the client side via JQuery's validation plugin and try to send a request to the database where I check the user availability via AJAX. The validation plugin works but something goes wrong when I requesting the database entries via AJAX, because if I press the "Send" button in the form I get the Error occurred alert on screen.
My registration.html code:
<form id="form" name="registration" action="" method="POST">
<label for="user_name">Nickname:</label><br>
<input type="input" size="40" maxlength="10" name="user_name" id="user_name" placeholder="Nickname"><br><br>
<label for="user_email">Email:</label><br>
<input type="email" size="40" maxlength="20" name="user_email" id="user_email" placeholder="Email address"><br><br>
<label for="user_password">Password:</label><br>
<input type="password" size="40" maxlength="50" name="user_password" id="user_password" placeholder="Passwort"><br>
<label for="confirmed_password">Confirm password:</label><br>
<input type="password" size="40" maxlength="50" name="confirmed_password" id="confirmed_password" placeholder="Passwort bestätigen"><br><br>
<input type="submit" name="register" value="Send">
</form>
<script src="./form_validation.js"></script>
My form_validation.js code:
$("#form[name='registration']").validate({
rules: {
user_name: {
required: true
},
user_email: {
required: true,
email: true
},
user_password: {
required: true,
minlength: 7
},
confirmed_password: {
required: true,
equalTo: "#user_password"
}
},
messages: {
user_name: 'Enter a nickname.',
user_email: {
required: 'Enter your email address.',
email: 'Enter a valid email address.',
},
user_password: {
required: 'Enter a password.',
minLength: 'At least 7 characters.',
},
confirmed_password: {
required: 'Confirm password.',
equalTo: 'Passwords have to match.',
}
},
submitHandler: function (form) {
$.ajax({
url:'./user.php',
type: "post",
data: $(form).serialize(),
success: function() {
alert("success");
console.log();
$("#result").html('Submitted');
},
error: function() {
alert("Error occured");
console.log();
$("#result").html('An error occured while submitting.');
}
});
}
});
});
My user.php code:
<?php
require_once __DIR__ . "./connection.php";
if (isset($_POST["register"]) && isset($_POST['user_name']) && isset($_POST['user_email']) && isset($_POST['user_password']) && isset($_POST['confirmed_password']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_pasword'];
$db = new DB_connection;
$sql = "SELECT * FROM user WHERE user_name = :user_name OR user_email = :user_email";
$statement = $db->conn->prepare($sql);
$statement->bindParam("user_name", $user_name);
$statement->bindParam("user_email", $user_email);
if ($statement->execute())
{
$sql = "INSERT INTO user (user_name, user_pass, user_email) VALUES (:user_name, :user_password, :user_email)";
$stmt = $db->conn->prepare($sql);
$stmt->bindParam(":user_name", $user_name);
$stmt->bindParam(":user_password", $user_password);
$stmt->bindParam(":user_email", $user_email);
if ($stmt->execute()) {
echo "New user inserted";
} else {
echo "Something went wrong!";
}
} else {
echo "Error!";
}
}
Found the solution. I just had to replace the include_once __DIR__ './connection.php'; with include_once __DIR__ '/../config/config.php';. What is strange is that no MYSQL error message appeared and other classes work without the include_once statement.
I am attempting to add validation for a non-input, custom selection. I have a series of images that the user clicks, which act as a checkbox, but do not actually have an input. I am using jQuery validate for the rest of my form and wanted to see if there was anyway that I can add validation, whether it is adding a method (I read jQuery validate only works on inputs) or something else that will work with one click of submit.
I am wanting something similar to this, but to work like jQuery validate.
if(checkValue.length < 1) {
alert("You need at least one interested selected.");
}
I tried putting the above if-statement above the rules section in the validation code, but it throws an error.
Does anyone have any alternative ideas that I could try?
//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
rules: {
first_name: {
required: true,
minlength: 2
}
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
if (data == 'Error!') {
alert(data);
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
.interest img {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">
Full code:
<section class="sec90">
<h3 class="subTC">Enter your information below.</h3>
<form action="" id="salesforce_submit" method="POST" enctype="multipart/form-data">
<input name="oid" type="hidden" value=""><input type="hidden" id="" id="interestValue" multiple="multiple" name="" value=""><input name="retURL" type="hidden"> <input name="lead_source" required="" type="hidden" value="Quote Form"> <input id="txt_medium" name="txt_medium" type="hidden" value=""> <input id="txt_source" name="txt_source" type="hidden" value=""> <input id="txt_campaign_name" name="txt_campaign_name" type="hidden" value=""> <input id="txt_term" name="txt_term" type="hidden" value=""> <input id="txt_content" name="txt_content" type="hidden" value="">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<div><input id="last_name" placeholder="Last Name*" class="input block" maxlength="80" name="last_name" type="text"></div>
<div><input id="email" placeholder="Email*" class="input block" maxlength="80" name="email" type="email"></div>
<div><input id="phone" placeholder="Phone* no dashes" class="input block" maxlength="12" name="phone" type="tel"></div>
<div><input id="zip" placeholder="Zip/Postal Code*" class="input block" maxlength="5" name="zip" type="text" pattern= "[0-9]{5}"></div>
<div><input id="company" placeholder="Company*" class="input block" maxlength="40" name="company" type="text"></div>
</section>
<section class="sec90">
<h3 class="subTC">What are you interested in?*</h3>
<div><input type="hidden" name="interestHidden" value=""></div>
<section class="sec90" id="up">
<h3 class="subTC">Describe your project*</h3>
<div><textarea id="description" name="description" placeholder="Provide as much detail as possible"></textarea></div>
<h3 class="subTC block">Have a .stp file or drawing example? Send it for quicker quote times.</h3>
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFile" data-multiple-caption="{count} files selected" multiple>
<label for="uploadedFile" class="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg><span class="marL5">Upload file</span></label>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<div class="margBot40"></div>
</section>
<input name="submit" class="block testB" type="submit" value="SUBMIT QUOTE">
</form>
JS:
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
var showMe = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
//Hidden interest input value
var checkLength = checkVal.length;
console.log(checkLength);
$('[name="interestHidden"]').val(checkLength);
var interestVal = $('interestValue').val()
interestVal = checkValue;
showMe = interestVal;
console.log('Hidden val is ' + showMe);
});
/*$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'));
});*/
$('#phone').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$text = $(this);
if (key !== 8 && key !== 9) {
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$text.val($text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
$('#phone').keyup(function() {
jQuery.validator.addMethod("alphanumeric", function(value, element) {
//return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
return this.optional(element) || /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/i.test(value);
}, "Numbers and dashes only");
});
$('#salesforce_submit').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
phone: {
required: true,
//digits: true,
minlength: 10,
alphanumeric: true
},
zip: {
required: true,
digits: true,
minlength: 5
},
company: {
required: true,
minlength: 2
},
interestHidden: {
required: true,
min: 1
}/*,
description: {
required: true,
minlength: 5
}*/
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
},
last_name: {
required: "Please enter your last name",
minlength: "Your last name seems a bit short, doesn't it?"
},
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
},
phone: {
required: "Please enter your phone number",
digits: "Please enter a valid phone number with only numbers",
minlength: "Your number seems a bit short, doesn't it?"
},
zip: {
required: "Please enter your zip code",
digits: "Please enter a valid zip code with only numbers",
minlength: "Your zip code seems a bit short, doesn't it?"
},
company: {
required: "Please enter your company name",
minlength: "Your company name seems a bit short. Please enter at least 2 characters"
},
interestHidden: {
required: "Please choose at least one interest",
min: "At least one interest needs chosen"
}/*,
description: {
required: "Please enter your project description",
minlength: "Your description seems a bit short, doesn't it?"
}*/
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
alert(data);
} else {
$('#salesforce_submit')[0].reset();
$('#consult-success').show();
$('#salesforce_submit').hide();
}
},
complete: function() {
//$("#salesforce_submit").submit();
location.href = "";
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
Since jQuery Validate only validates select, textarea, and various types of input elements1, your only option is to give it what it wants.
Create a hidden element...
<input type="hidden" name="myImage" value="0" />
When the user clicks your image, use jQuery to manipulate the value of a type="hidden" input element...
$('#photo').on('click', function() {
$('[name="myImage"]').val('1');
});
And then programmatically validate its value instead. Since clicking on the image will not cause any validation, you can use the .valid() method to trigger validation on these hidden elements...
$('[name="myImage"]').valid();
You will need to leverage the ignore option since the plugin will not validate hidden elements by default. ignore: [] will effectively disable this and force the plugin to validate all hidden elements...
$('#salesforce_submit').validate({
ignore: [],
rules: { ....
Of course, you'll also need to have rules in place that properly validate the value of your hidden element.
Since the message will be placed near the hidden element, you'll have to leverage the errorPlacement function to place this message conditionally.
$('#salesforce_submit').validate({
ignore: [],
errorPlacement: function(error, element) {
if (element.attr('name') == 'myImage') {
// placement for hidden element
} else {
// default
error.insertAfter(element);
}
}
rules: { ....
1 newer versions of the plugin also support elements with the contenteditable attribute.
What about this, give all the checkboxes you trigger the same name e.g. "box". Add this custom rule "img_check":
jQuery.validator.addMethod("img_check", function() {
$(input[name='box']).each( function(){
if $(this).is(':checked') {
return true
}
})
// No box was checked
return false
}, "Please check at least one box");
Then add this rule:
rules: {
first_name: {
required: true,
minlength: 2
},
box[]: {
img_check: true
}
},
Why don't you check checkValue before going ahead with the submission process?
//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
rules: {
first_name: {
required: true,
minlength: 2
}
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
if(checkValue.length>0){
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
if (data == 'Error!') {
alert(data);
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}else console.log('Please select at least one interest');
}
});
.interest img {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">
I am using Jquery validation plugin to validate, I am trying to validate all fields on click of submit button.
But if you see in fiddle by typing wrong email format and if you move to password that next input field it gives message saying "Please enter a valid email address", which I dont want.
I want all fields to validate on click of submit button till then submit button should be disabled when all fields are valid then allow user to click and validate once again to check fields.
is it possible to invoke validaion plugin on submit?
Here is what I tried so far
Html code
<form action="" method="post" id="register-form" >
<div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>
my js code
$(function() {
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
});
Try this..
$(function() {
onfocusout: false,
onkeyup: false,
onclick: false
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
},
errorPlacement: function(error,element) {
return true;
},
invalidHandler: function(event, validator) {
alert(validator.valid());
//if(validator.valid()) show your modal then use validator.errors() to show custom errors
}
});
});
This simple validation might work for you. Please have a look.
$('tab').addClass('inactive);
$('input[type="submit"]').click(function(){
//Onclick get all the input value
var firstname = $("#firstname").val(),
lastname = $("#firstname").val(),
email = $("#email").val(),
psw = $("#password").val(),
regx = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
//If anything is invallid
if(firstname == "" || lastname == "" || email == "" || !regx.text(email) || psw == ""){
if(firstname == ""){ //if firstname is blank
alert("Please enter your first name");
}
if(lastname == ""){ //if lastname is blank
alert("Please enter your last name");
}
if(email == ""){ //if email is blank
alert("Please enter email id");
}
if(!regx.text(email)){ //if email is not in proper format
alert("Please enter valid email id");
}
if(psw == ""){ //if password is blank
alert("Please enter password");
}
return false; //form will not submit, it will return false
}else{
$('.tab').addClass('active').removeClass('inactive'); //if for is valid, add/remove class to the element
}
});
I am using jQuery Validation plug-in in my two step registration form.
On "First Step" I'm checking username and email availability with remote function.
Here is the bug (or me!):
If username exist in database and email is not, when I click "next" button the script letting me go to second step. (It shouldn't because username exist!)
but;
If username not exist and email is exist in the database, It's stops me there and warns me email is exist. So it's working.
If both username and email exist in the database, also stops me. So again working.
Here is code I'm using;
HTML:
<div class="tab-content">
<p>Page.</p>
<form class="form-horizontal" onsubmit="return false;" action="" method="post" id="myform">
<div id="stepusername">
<p>This is step 1</p>
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="email" class="form-control" id="email" name="email" placeholder="email" autocomplete="off"><br>
<p><a class="btn btn-primary next">Go to step 2</a></p>
</div><!-- signup_one ends -->
<div id="stepemail">
<p>This is step 2</p>
<input type="password" class="form-control" id="password" name="password" placeholder="password" autocomplete="off"><br>
<input type="password" class="form-control" id="conf_password" name="conf_password" placeholder="password" autocomplete="off"><br>
<input class="btn btn-success next" type="submit" value="Finish">
</div><!-- step2 ends -->
</form>
<div id="stepsuccess">
<p>Show result here.</p>
</div><!-- success ends -->
</div><!-- tab-content ends -->
Java Script:
<script type="text/javascript">
// jQuery.validate script, does client-side validation
$(document).ready(function(){
$(".next").click(function(){
var form = $("#myform");
form.validate({
errorElement: 'div',
errorClass: 'formerror',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass("has-error");
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass("has-error");
},
rules: {
username: {
required: true,
remote: {
url: "check-username.php",
async: false,
type: "post", }
},
password : {
required: true,
},
conf_password : {
required: true,
equalTo: '#password',
},
email: {
required: true,
remote: {
url: "check-email.php",
async: false,
type: "post", }
},
},
messages: {
username: {
required: "Username required",
remote: "Taken username.",
},
password : {
required: "Password required",
},
conf_password : {
required: "Password required",
equalTo: "Password don't match",
},
email: {
required: "Email required",
remote: "Taken email.",
},
}
});
if (form.valid() === true){
if ($('#stepusername').is(":visible")){
current_fs = $('#stepusername');
next_fs = $('#stepemail');
}else if($('#stepemail').is(":visible")){
current_fs = $('#stepemail');
next_fs = $('#stepsuccess');
}
next_fs.show();
current_fs.hide();
}
});
});
</script>
Update:
check-username.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['username'];
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
check-email.php
<?php
error_reporting(E_ERROR | E_PARSE);
try {
$handler = new PDO('mysql:host=localhost;dbname=users', 'root', '');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
$request = $_REQUEST['email'];
$query = $handler->query("SELECT * from usertable WHERE email='$request'");
$results = $query->fetch(PDO::FETCH_ASSOC);
if(empty($request)) {
echo 'false' ;
}else {
if ($results == 0) {
$valid = 'true';
}
else {
$valid = 'false';
}
echo $valid ;
}
?>
Also jsFiddle if you like to see: http://jsfiddle.net/noptpece/
$query = $handler->query("SELECT * from usertable WHERE username='$request'");
This line doesnt look, if a user exists, whos name equals the content of $request, it looks up if the user with the name "$request" exists, the same with the e-mail.
String composing in PHP works differently, you should write
$query = $handler->query("SELECT * from usertable WHERE username=".$request);
Also you should never ever use a MySQL query like this, because its the easiest thing of the world to inject SQL code and destroy your whole database.
Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/