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;
!!!
Related
I have a App where I want the combination of three fields: rollyear, rollfaculty and rollno in a table to be unique. For that, I did the following in the migration file:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('rollyear');
$table->string('rollfaculty');
$table->string('rollno');
$table->unique(['rollyear','rollfaculty','rollno']);
});
This is working as expected but whenever duplicate values are supplied to the specified fields, I get a full page Integrity constraint violation error.
How can I handle this error and give a simplified error message to the user as in following image?
Please put below code in your controller where you store users details.
$chkUniqueEmailId = DB::table('users')->where('email', '=', $request->email)->first();
if(!empty($chkUniqueEmailId)){
return redirect()->route('auth.register')->withFlashDanger("This email address already exists.");
}
add validate through jQuery
save this file on your public/js folder
Here's a link!
and ad another validation file for register
// validate signup form on keyup and submit
$("#addUserForm").validate({
rules: {
name:{
required:true
},
email: {
required: true,
email: true,
remote: {
url: "/checkuser",
type: "get"
}
},
password: {
required: true,
minlength: 5
},
image: {
required:true,
accept: "jpg|jpeg|png|JPG|JPEG|PNG"
}
},
messages: {
name: {
required:"Please enter a name"
},
email: {
required:"Please enter a email address",
email:"Please enter a valid email address",
remote:"Email Already Exist"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
image: {
required: "Please provide a profile image",
accept: "Please upload only jpg,jpeg,png"
}
}
});
add /checkuser
public function checkUser()
{
$user = User::where('email', request('email'))->exists();
if($user){
return 'false';
}
else {
return 'true';
}
}
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 have a file input box which is not required for validation. But if the input box is not empty then i want the validation for file type and file size to be executed.
jQuery(document).ready(function(){
jQuery.validator.addMethod("accept", function(value, element, param) {
return value.match(new RegExp("." + param + "$"));
});
jQuery.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
});
jQuery('#adminform').validate({
rules: {
resume: {
required: false,
accept: "(doc|docx|pdf)",
filesize: 1024 //1048576
}
},
......................
resume: {
accept: "File type not supported",
filesize: "File cannot be more than 1MB!"
},
For now the problem is that even if i don't supply any input and leave it empty, i get the rule "accept" executed i.e i get the message "File type not supported".
Try this..Not empty check ensures that if field is left blank then validation won't be performed
$('input[type="file"]').on("change", function() {
if ($this.val() !== '') {
//do validation stuff here!!
}
});
Tryout this if this helps:
$("#commentForm").validate({
rules: {
name: "required",
file: "required",
name: {
required: true,
minlength: 2
},
file: {
required: false,
minlength: 5
}
},
messages: {
name: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
file: {
required: "Please select a file",
minlength: "Your password must be at least 5 characters long"
}
},
submitHandler: function(form) {
if ($('#cfile').val() != "") {
$("#commentForm").validate({
rules: {
file: "required",
file: {
required: true,
minlength: 5
}
},
messages: {
file: {
required: "Please select a file"
}
}
});
$(form).submit();
} else {
alert('file missing.');
}
}
});
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.