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';
}
}
Related
Update: The email address check for the email field is returning "email address is already in use" upon entering an address regardless if the email address is new or exists in the mySQL database. I would like it to only return the error when an email exists in the email field of the users table in the database.
The current code for the signup page is:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
$().ready(function(){
$("#register").validate({
errorElement: 'span',
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.insertAfter($(".term"));
} else {
error.insertAfter(element);
}
},
rules: {
su_email : {
required: true,
email: true,
remote: "/email_check.php"
},
su_password : {
minlength: 6,
required: true
},
su_conpassword : {
equalTo : "#su_password"
},
su_name : {
minlength: 3,
required: true
},
su_phone : {
required: true
},
su_city : {
required: true
},
su_country : {
required: true
},
su_gender : {
required: true
},
su_quest : {
required: true
},
su_ans : {
required: true
},
su_terms : {
required: true
}
},
messages: {
su_email: {
required: "Please enter your email address",
email: "Please enter a valid email address",
remote: jQuery.validator.format("{0} is already in use")
},
su_password: {
required: "Provide a password",
minlength: jQuery.validator.format("Enter at least {0} characters")
},
su_conpassword: {
equalTo: "Repeat your password"
},
su_name: {
required: "Enter your full name",
minlength: jQuery.validator.format("Enter at least {0} characters")
},
su_phone: {
required: "Enter your phone number"
},
su_city: {
required: "Enter your city"
},
su_country: {
required: "Select your country"
},
su_gender: {
required: "Select your gender"
},
su_quest: {
required: "Select a security question"
},
su_ans: {
required: "Select a security answer"
},
su_terms: {
required: "You must agree to terms to join"
}
}
});
$('.condition').click(function () {
if ($(this).is(':checked')) {
$('#termscondition').dialog({
modal: true,
width: 600,
buttons: {
Ok: function() {
$( this ).dialog('close');
}
}
});
} else {
$('#termscondition').dialog('close');
}
});
});
</script>
<?php
include('includes/inc-public.php');
include('includes/classes/class.user.php');
$user = new User();
$email = $_GET['su_email'];
$valid = false;
header('Content-Type: application/json');
if(!is_null($email)){
$is_valid = $user->get_email($email);
if($is_valid){
echo json_encode($is_valid);
}
else{
echo json_encode($valid);
}
};
?>
signup form when a new email address is being entered in the email field
users table of mysql database
From documentation:
The serverside response must be a JSON string that must be "true" for valid elements, and can be "false", undefined, or null for invalid elements, using the default error message. If the serverside response is a string, eg. "That name is already taken, try peter123 instead", this string will be displayed as a custom error message in place of the default.
So you need to change your is_valid to true.
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;
!!!
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;
}
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.
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
}
?>