jquery validate remote function - php

I'm using the validate plugin with my form and i'm facing some difficulties with the remote function.
I'm using it to ajax post to a file which in turn returns true or false.
When i enter an email that is taken or taken username, it will alert with the right error message.
But when ajax returns true, it wont do anything. That is, until i click the email inputbox, and click out to re-trigger it. then it will validate it. Ive tried alot of different solutions, like onblur triggers etc.. thing is, that all the other inputfields work out of the box, no problem. the checkmail file is very straight forward, echoing either true or false, no real issue there..
It's an e-mail check and a username check and the rules are the same for both, except the file it calls :
$("#registerHere").validate({
onkeyup: false,
onblur: true,
rules:{
usr_name: {
required: true,
minlength: 5,
remote: {
url: "inc/checkuser2.php",
type: "post",
async: false
}
},
full_name:"required",
blog_name:"required",
user_email: {
required: true,
email: true,
remote: {
url: "inc/checkmail.php",
type: "post",
async: false,
data: {
user_email: function() {
return $("#user_email").val()
}
}
}
},
pwd:{
required:true,
minlength: 6
},
cpwd:{
required:true,
equalTo: "#pwd"
},
gender:"required"
},
messages:{
usr_name:{
required: "Velg et brukernavn",
minlength: "Minimum 5 bokstaver",
remote: "Dette brukernavnet er opptatt"
},
full_name:"Skriv inn navnet ditt",
blog_name:"Velg en tittel til bloggen din",
user_email:{
required: "Fyll inn e-post adressen din",
email:"Dette er ikke en gyldig e-post adresse",
remote:"Denne e-posten finnes allerede"
},
pwd:{
required:"Velg passord",
minlength:"Passordet må ha 6 tall og bokstaver"
},
cpwd:{
required:"Gjenta passordet",
equalTo:"Passordene er ikke like"
},
gender:"Velg kjønn"
},
errorClass: "help-inline",
errorElement: "span",
highlight:function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
}
});
Here's my checkmail.php (will sanitize once it works):
$duplicate = mysql_query("select count(*) as total from users where user_email='$user' ") or die(mysql_error());
list($total) = mysql_fetch_row($duplicate);
if ($total > 0)
{
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
exit;
It's not critical, as the form seems to submit, but i would hate leaving it like this when i am so close to what i want!
Hope this was understandable and i would really appreciate any help as ive read and tried everything google gave me!

I believe when it comes to AJAX in the form validation plugin, you'll need to use a callback and return the element.
onkeyup: function(element) {
this.element(element);
}
The downside to this is that it will execute your AJAX on every keyup, so you'll want to perform some kind of check inside your callback. For example:
onkeyup: function(element) {
if ( element.type == 'password' )
this.element(element);
else
return true;
}

Related

how to check if a username exits using jquery validation and laravel

Ok so I am using jquery validation plugin to validate my form and it is working good so far my only problem is that i want to check if a username exits while the user is entering data into the form. I have solved the problem already using jquery and plain php. Now i want to do the samething using jquery validation and laravel framework. Here is a sample of my js. As always any help would be appreciated.
var fnameregex = /^[a-z -]+$/i;
var lnameregex = /^[a-z'-]+$/i;
var usernameregex = /^[a-z0-9_'-]+$/i;
var emailregex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var passregex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.{8,})");
var aos = '';
$.validator.addMethod('firstname_regex', function(value,element){
return this.optional(element) || fnameregex.test(value);
},'This name is not valid.')
$.validator.addMethod('lastname_regex', function (value,element) {
return this.optional(element) || lnameregex.test(value);
},'This name is not valid')
$.validator.addMethod('username_regex', function (value,element) {
return this.optional(element) || usernameregex.test(value);
},'This username is not valid')
$.validator.addMethod('password_regex', function (value,element) {
return this.optional(element) || passregex.test(value);
},'Passwords must be eight characters or more contain one uppercase, one numeric number and one lowercase.')
$(function(){
$('#signupform').validate({
rules:{
firstname:{
required:true,
firstname_regex:true,
nowhitespace:true,
minlength:3,
},
lastname:{
required:true,
lastname_regex:true,
nowhitespace:true,
minlength:3,
},
username:{
required:true,
username_regex:true,
nowhitespace:true,
remote:{
url:"checkusers",
type:"post"
}
},
email:{
required:true,
email:true,
nowhitespace:true,
},
password:{
required:true,
password_regex:true,
nowhitespace:true,
},
passconfirm:{
required:true,
password_regex:true,
nowhitespace:true,
equalTo:"#password",
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
$(element).closest('.form-control').css("border-color","#a94442");
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-control').css("border-color","#00b8e6");
// $('#firstname').css("border-color","#00b8e6");
},
messages:{
passconfirm:{
equalTo:"Please ensure your passwords match."
},
firstname:{
minlength:"Please enter a valid name."
},
lastname:{
minlength:"Please enter a valid name."
},
username:{
remote: "This username already exits."
}
}
});
})
i sent a post request to checkusers now i want to tell laravel what to do when it receives such a request if the username is already taken the it should return a response of false therefore the remote validation would fail and give the proper error else return true and it passes the remote validation here is a sample of my route in laravel.
Route::post('checkusers',function(){
$user = users::all()->where('username', Input::get('username'))->first();
if ($user) {
echo "false";
} else {
echo "true";
}
});
i will also include a php script i have which does the work i only need someway of doing the same thing in laravel.
require_once "connect.php";
if(isset($_POST['username'])) {
$username = $_POST['username'];
$result =$conn->query("SELECT username FROM users WHERE username='$username'");
if ($result->num_rows ==0){
echo 'true';
}
else {
echo 'false';
}
}

JQuery remote validation not working

I had a registration form which i added a JQuery validate plugin remote validation in. The purpose of the remote validation is to check if the email/and username entered by the user already exists in my database(i.e is already in use), and will return an error message if it is.The form was working before i added the remote validation.
Now, i am unable to submit the form even when all the data i've entered is correct, and to add insult to injury, no error messages appear when i enter an email that already exists in my database.
My JQuery code:
$(document).ready(function(){
<!--AJAX Call to retrieve type & subtype of industries-->
$("#type").load("getregtype.php");
$('#type').change(function(){
var type=$('#type').val();
$('#subtype').load('getregsubtype.php?type='+type);
});
<!--End of AJAX Call -->
<!--JQuery validation of registration form-->
<!--Set default message for 'equalTo' errors-->
$.extend($.validator.messages, { equalTo: "The values you entered do not match." });
$("#regform").validate({
// Specify the validation rules
rules: {
username: "required",
password: {
required:true,
minlength:6,
},
cpassword: {
required: true,
minlength: 6,
equalTo: "#password"
},
email: {
required: true,
email: true,
remote:"emailcheck.php"
},
cemail: {
required: true,
email: true,
equalTo:"#email"
},
type: {
required: true
},
subtype: {
required: true
},
name: "required"
},
// Specify the validation error messages
messages: {
username: "Please enter a username",
email: {
required:"Please enter an email address",
email:"Please enter a valid email address",
remote:jQuery.format("{0} is already in use")
},
cemail: {
required:"Please enter an email address",
email:"Please reenter your email address",
},
password: {
required: "Please enter a password",
minlength: "Your password must be at least 6 characters long"
},
cpassword: {
required:"Please reenter your password",
minlength: "Your password must be at least 6 characters long"
},
name: "Please enter the name of your business"
},
submitHandler: function(form) {
form.submit();
}
});
});
My PHP page that is called by remote.
<?php
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `testdb`.`business` WHERE `Email` = :email");
$query->bindValue(":email",$_GET['email']);
$query->execute();
$count=$query->rowCount();
$mail=$_GET['email'];
print_r($mail);
echo"$count";
if($count>0)
{
echo json_encode('false');
}
else
{
echo json_encode('true');
}
?>
Things tried
print_r($mail) and echo"$count"; both return the correct value.I've also tried
echo json_encode(true);
as well as
return true;
EDIT
Some more things i've tried.
echo true;
I've also tried to pass in the value of the email directly through the url, on the off chance that the value was not being passed to 'emailcheck.php' by doing
email: {
required: true,
email: true,
remote:"emailcheck.php?email=test#test.com"
},
but my form still doesn't work.
I appreciate any insight to my problem.
Thanks!
Your PHP script expects a GET parameter with name email. Just to eliminate the possibilities of errors here, you can set that explicitly in the jQuery code :
rules: {
/* Code skipped ... */
email: {
required: true,
email: true,
type: "get",
remote:"emailcheck.php"
data: {
email: function() {
return $("#email").val();
}
}
},
/* ... */
Make sure that $('#email') really matches your form input.
You can also check the response with Firebug or an equivalent tool (just hit F12 on your browser window and see what comes up), you might want to ensure that the mimetype of the response is application/json.
First of all check js error in your console, if nothing is wrong check also what your script send and what he receive from php
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $("[name='email']").val();
}
}
}
and from the PHP file check-email.php just echo true or false like this:
echo 'false';
or
echo 'true';
not echo false; or echo true;
!!!

jquery validation, submit button not working in php

I click the button and nothing happens. If I take out the validation code, then clicking the button works and it falls back to the PHP validation that I have implemented. I coded up the jquery validation first and it worked, then I coded up the PHP side. But then the jquery validation stopped working after the PHP side is okay.
Can someone help?
I tried adding
submitHandler: function(form) {
form.submit();
}
like this:
submitHandler: function(form) {
form.submit();
},
rules: {
...
}
But nothing happened.
Here is the relevant code, let me know if anything is unclear, thanks! I've been stuck on this for a while now.
if (isset($_POST['submit']))
{
foreach($_POST as $key=>$value)
{
unset($_SESSION[$key]);
$_SESSION[$key] = $value;
}
$errors = validation($job);
if (count($errors) == 0)
{
sendEmail($job);
sendEmailToApplicant($job);
}
}
$output = "
<script src='http://code.jquery.com/jquery-latest.js'></script>
<script type='text/javascript' src='http://jzaefferer.github.com/jquery-validation/jquery.validate.js'></script>
<script type='text/javascript'>
jQuery.validator.setDefaults({
debug: true,
success: 'valid'
});
jQuery.validator.addMethod('phoneUS', function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, '');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, 'Please specify a valid phone number');
</script>
<script>
$(document).ready(function(){
$('#applicationForm').validate({
rules: {
firstName: {
required: true,
rangelength: [2, 15]
},
lastName: {
required: true,
rangelength: [2, 15]
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
website: {
url: true
}
}
});
});
</script>
<form id='applicationForm' name='applicationForm' method='post' enctype='multipart/form-data'>
...
<input id='submit' type='submit' name='submit' />
</form>";
really quick to try. not sure if this is the issue since I really didnt look too close, but why is there jQuery. in some actions if you dont have a jquery.noConflict.
try changing those to just $ like this maybe:
<script>
$(document).ready(function(){
$('#applicationForm').validate({
rules: {
firstName: {
required: true,
rangelength: [2, 15]
},
lastName: {
required: true,
rangelength: [2, 15]
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
website: {
url: true
}
}
});
$.validator.setDefaults({
debug: true,
success: 'valid'
});
$.validator.addMethod('phoneUS', function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, '');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, 'Please specify a valid phone number');
});
Checking whether a post has been made is done using the following code:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
Checking for the existance of the submit button is very unreliable.

How can we stop the HTML Form Submit button, when any of the value will not be accurate

I would like to stop the submit button function, when we got any error in HTML form elements (like captcha). We have several functions in our script, let me explain in details.
Check the data validation only captcha security code configured with PHP (through - jquery-1.3.2.js && - validate.js)
Send data through AJAX call (through - ajaxSubmit.js)
now i would like to stop the script, when any of the user filled the wrong value in Captcha text. we just simply disable the submit button and get message ("Form Not Filled Properly...")
UPDATED VALIDATION - please check only with Captcha codes
<script type="text/javascript">
$.validator.addMethod('myEqual', function (value, element) {
if ($('#password-password').val() == $('#password-password-confirm').val()) {
return true;
} else return false;
}, 'Your password does not match.');
$(document).ready(function() {
$('#password-clear').show();
$('#password-password').hide();
$('#password-clear').focus(function() {
$('#password-clear').hide();
$('#password-password').show();
$('#password-password').focus();
});
$('#password-password').blur(function() {
if($('#password-password').val() == '') {
$('#password-clear').show();
$('#password-password').hide();
}
});
$('#password-clear-confirm').show();
$('#password-password-confirm').hide();
$('#password-clear-confirm').focus(function() {
$('#password-clear-confirm').hide();
$('#password-password-confirm').show();
$('#password-password-confirm').focus();
});
$('#password-password-confirm').blur(function() {
if($('#password-password-confirm').val() == '') {
$('#password-clear-confirm').show();
$('#password-password-confirm').hide();
}
});
var validator = $("#signupform").validate({
//ignore: ".ignore",
rules: {
username: {
required: true,
minlength: 5
},
captcha: {
required: true,
remote: "includes/process.php"
},
password: {
required: true,
minlength: 5
},
passwordconfirm: {
required: true,
minlength: 5,
myEqual: true
},
email: {
required: true,
email: true
}
},
messages: {
captcha: "Correct captcha is required. Click the captcha to generate a new one",
username: {
required: "Enter a username",
minlength: jQuery.format("Enter at least {0} characters"),
},
password: {
required: "Provide a password",
rangelength: jQuery.format("Enter at least {0} characters")
},
passwordconfirm: {
required: "Provide a password",
rangelength: jQuery.format("Enter at least {0} characters")
},
email: {
required: "Please enter a valid email address",
minlength: "Please enter a valid email address"
}
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
if ( element.is(":radio") )
error.appendTo( element.parent().next().next() );
else if ( element.is(":checkbox") )
error.appendTo ( element.next() );
else
error.appendTo( element.parent().next() );
},
submitHandler: function() {
alert("submitted!");
},
// specifying a submitHandler prevents the default submit, good for the demo
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html("").addClass("checked");
// form.submit();
}
});
});
Please suggest me proper code for our requirement.
With jQuery:
$("#formid").submit(function (){
if(!your condition){
return false;
}
});
Use the onSumbit attribute o fteh form. Assign it the function that you use to check for correct form completion. If the form is correctly filled out then return true; otherwise return false. False will stop the form from being submitted. You could display the required message just before returning false.

jQuery Validation plugin addMethod

I'm trying to add a new method to jQuery validation plugin with the codes below. My goal is to check whether the email address has already existed in the database(MySQL). If it is, it will inform the user to register for another email address. Somehow, the result that always returns is "Email is already taken".
These are the codes in validate.js:
$(document).ready(function(){
$.validator.addMethod("uniqueEmail", function(value, element) {
$.ajax({
type: "POST",
url: "availability.php",
data: value,
success: function(exist)
{
if(exist>0) {
return true;
} return false;
}
});
} ,"Email is already taken");
$('#signup form').validate({
rules: {
firstname: {
required: true,
minlength:3
},
lastname: {
required: true,
minlength: 3
},
affiliation: {
required: true,
},
occupation: {
required: true,
},
email: {
required: true,
email: true,
uniqueEmail: true
},
password: {
minlength: 6,
required: true
},
repassword: {
equalTo: "#password"
}
},
messages: {
firstname: {
minlength: "Your first name should be more than 3 characters"
},
lastname: {
minlength: "Your last name should be more than 3 characters"
},
},
success: function(label) {
label.text('OK!').addClass('valid');
}
});
});
And these are the codes in my php file:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/db.inc.php';
$email = strtolower($_POST['email']);
$email = mysqli_real_escape_string($link, $email);
$sql = "SELECT * FROM bradduser WHERE email='$email'";
$result = mysqli_query($link, $sql);
$num = mysqli_num_rows($result);
echo $num;
?>
You can't quite do this here with a custom method because you need the validation plugin to know this is a remote (or more importantly, an asynchronous) request.
Luckily it has built-in functionality to help. Instead of a custom method you can use remote here, so leave of the custom method altogether and change out this:
uniqueEmail: true
for this:
remote: { url: "availability.php", type: "post" }
Then add the error message to messages like this:
email: { remote: "Email is already taken" }
Also change your PHP side to match, returning true or false, like this:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/braddclient/includes/db.inc.php';
$email = strtolower($_POST['email']);
$email = mysqli_real_escape_string($link, $email);
$sql = "SELECT * FROM bradduser WHERE email='$email'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0) {
echo "false"; //validation fails, email in use
} else {
echo "true"; //validation passes
}
?>

Categories