I want to make validation on Email using jQuery
A regular validation (required) and other verification using Ajax
first function to validate if email exist and other to verify is not in black list (other table)
$('#form').validate({
errorElement: 'span',
rules:{
Email: {
required: true,
email: true,
remote: '/ifexist'
}
},
messages:{
Email:{
remote:'email already exist'
}
}
});
I try to add other remote like this, but it doesn't work
remote: '/ifexist'
remote: '/inblacklist'
My php code
if(isset($_GET['Email'])){
$is_valid = Member::inblacklist($email);
header('Content-Type: application/json');
echo json_encode($is_valid);
}else{}
Any solution ?
This answer to this question claims that the jQuery validation plugin does not support multiple remotes (I haven't seen any credible evidence to prove neither the claim nor otherwise, yet). I'd have done something as follows if I was to handle your case.
$('#form').validate({
errorElement: 'span',
rules:{
Email: {
required: true,
email: true,
remote: {
url:'/ifexist',
type:'POST', //Or whatever
data:function(){
return $("#email").val(); // The value of the email field
},
dataType:"JSON", // So that you can return a JSON object from the backend
dataFilter:function(responseData){ // Handles the response
/* Assume you return a JSON object as follows
* {"isValid":false, "reason":"blacklisted"}
* or may be
* {"isValid":false, "reason":"duplicate"}
*/
alert(responseData.reason); // Or whatever
return responseData.isValid; // validation result
}
}
}
},
// Rest of the validation logic
What happens here is that, you take control the response from the backend's validation routine and handle it as you desire.
The plugin is almost fully customizable. Refer to the documentation for futher details.
EDIT (after updates to the original question)
Backend in php may be something as follows.
if(isset($_POST['Email'])){
$email = $_POST['Email'];
$response = null;
$isInBlackList = Member::inblacklist($email);
if($isBlackList){
// User is in the blacklist
$response = array("isValid"=>false, "message"=>"This email is blacklisted!"); // Initialize $response
}
else{
$alreadyExists = Member::alreadyExists($email); // You have to implement this.
if($alreadyExists){
// Email already exists
$response = array("isValid"=>false, "message"=>"This email is already in user"); // Initialize $response
}
else{
// We found a valid email
$response = array("isValid"=>true);
}
}
header('Content-Type: application/json');
echo json_encode($response);
}else{}
Notice the usage of php array() to encapuslate the response and return that as JSON.
Related
This question already has answers here:
How to respond to jQuery Validation remote?
(1 answer)
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 2 years ago.
I'm using the jQuery validator's remote method to determine if an email address already exists in our SaaS platform.
The code below is what we are using and it's fine. However, we would like to ideally return some information about the existing user, so that we may display a link to the existing patient's profile.
I've scoured the validator docs and can't seem to find any way to handle return parameters other than true/false. Is this a limitation of the remote method?
jQuery
form.validate({
rules: {
email: {
remote: {
url: "CheckEmailExists.php",
type: "post"
}
}
},
messages: {
email: {
remote: "This email address is already assigned to an existing patient"
}
},
});
PHP
$existingUserQuery = "SELECT tbl_patients.patient_id FROM tbl_patients WHERE tbl_patients.patient_email = :email";
$getUser = $pdo->prepare($existingUserQuery);
$getUser->bindparam(":email", $email);
$getUser->execute();
$numCount = $getUser->rowCount();
if ($numCount > 0) {
echo 'false';
} else {
echo 'true';
}
You can create a custom method and within the method do run your own remote call via AJAX. Then in your php, return a JSON object with the values that you want to use.
jQuery.validator.addMethod("validatemmail", function(value, element) {
var _is_valid = false;
var qry = {"email" : value};
$.ajax({
type: "POST",
url: "CheckEmailExists.php",
data: qry,
done: function(data){
if(data.error == "new"){
_is_valid = true;
console.log(data.patient_name);
}
else{
_is_valid = false;
}
return this.optional(element) || _is_valid );
}
});
}, "This email address is already assigned to an existing patient");
$('validatorElement').validate({
rules : {
email : { validatemmail : true }
}
});
Your PHP:
$return = [];
if ($numCount > 0) {
$return["error"] = "exists";
$return["patient_name"] = "John";
} else {
$return["error"] = "new";
}
header('Content-Type: application/json');
echo json_encode($return);
The original idea:
jQuery Validate Plugin - How to create a simple custom rule?
I am using CodeIgniter with jQuery validation. I am using remote to check mobile number and email id is already available or not in the database. So there is no issue when the user registers. I am getting the issue on the edit page.
On the edit page, I just change the name and address but mobile number and email id both are showing already exist. I haven't change mobile and email. I know it will call the controller to check mobile and email are available or not but is there any other way to handle this issue?
I mean, not to check the previous data and check current data if the user enters anything in the field.
I want to check user against the database when creating the account, but NOT check user against the database when editing the account.
$("#edit_member").validate({
errorElement: 'div',
rules: {
name: {
required: true,
alphabets: true,
minlength: 3
},
email: {
required: true,
Email: true,
remote: {
url: baseUrl + "/AddMember/isEmail",
}
},
phone: {
required: true,
number: true,
minlength: 10,
maxlength: 10,
remote: {
url: baseUrl + "/AddMember/isMobile",
// async: false
}
},
address: {
required: true,
minlength: 10
}
},
messages: {
email: {
remote: "Email already Exists"
},
phone: {
remote: "Mobile no already Exists"
},
},
submitHandler: function(form) {//form.submit();}
});
Controller
function isEmail()
{
$email = trim($this->input->get('email'));
$result = $this->addmember_model->isEmail($email);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
function isMobile()
{
$mobile = trim($this->input->get('phone'));
$result = $this->addmember_model->isMobile($mobile);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
Model
function isEmail($email)
{
$result = $this->db->where(['email'=>$email,'is_status'=>1])
->get('members')
->row();
return $result;
}
function isMobile($mobile)
{
$result = $this->db->where(['phone'=>$mobile,'is_status'=>1])
->get('members')
->row();
return $result;
}
Use PHP to determine if the page is Editing or Creating and set a variable as such. You could look at a URL segment with the URI Class.
<?php
$create = ($this->uri->segment(3) == "create") ? TRUE : FALSE;
?>
Then use PHP to write the relevant rule(s) for that particular version of the View.
$("#edit_member").validate({
....
rules: {
....
email: {
required: true,
Email: true,
<?php if ($create) : ?>
remote: {
url: baseUrl + "/AddMember/isEmail",
}
<?php endif; ?>
},
....
The above only works when this part of the JavaScript is in the View file and not included from an external JavaScript file.
Otherwise, if .validate() is part of an externally included JavaScript file, then you can use the .rules() method instead.
After the JavaScript includes (after .validate() invoked), programmatically remove the remote rule.
<?php if ($edit) : ?>
<script>
$(document).ready(function() {
$('[name="email"]').rules('remove', 'remote');
});
</script>
<?php endif; ?>
I'm attempting to use jQuery's remote validation method for a basic (well, should be) ajax call to some server-side logic. Now, where my situation gets peculiar is that i'm using SlimFramework and so I'm posting to a route, not a direct script page.
Here is the JS:
rules: {
email: {
required: true,
email: true,
remote: {
url: 'http://localhost:3000/email/check',
async: false,
type: 'post',
dataType: 'json',
data: {
email: function() {
return $('#email').val();
}
}
}
}
}
messages: {
email: {
required: 'Please enter an email address.',
remote: 'This email is already taken.'
}
}
Here is my server-side logic which I am almost certain is correct:
$app->post('/email/check', function() use ($app) {
$request = $app->request;
$email = $request->post('email');
$response = '';
$user = $app->user
->where('email', $email)
->first();
if($user) {
$response = false;
} else {
$response = true;
}
header("HTTP/1.1 200 OK");
header('Content-Type: application/json');
echo json_encode($response);
});
UPDATE
To be more specific, when I check the network response in the inspector, its seems the request is being made successfully:
However, The remote validation message that i specified in the messages property of the validation object is not being thrown...
Any suggestions as to why it is not functioning?
I'm having some strange problems using the validation plugin with jquery. This seems to have been asked a few times, but i cannot find the answer to my problem. I've got a form, and I am trying to see if the email has already been entered - if it has, the user should not be able to submit the form. I'm using FirePHP to output various variables. This is where I notice that the return value of my query is always "1" (which is wrong). However, when I manually query my db (using PhpMyAdmin), the correct answer ("0") comes up.
Here is my js:
// validate signup form on keyup and submit
$("#register").validate({
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
},
messages: {
......
email: {required: "Please enter an email address", email: "Please enter a valid email address", remote: "This email is already registered" },
}
}
});
});
And here is my php after the db connection stuff...
$form_email = $_GET['email'];
fb($form_email);
$sql = "SELECT COUNT(*) AS num_rows FROM users WHERE email = " . "'" . $form_email . "'";
fb($sql);
$result = $conn->query($sql);
fb($result->num_rows);
if ($result->num_rows == 0) {
echo 'true';
fb("true");
} else {
echo 'false';
fb("false");
}
The count is always returned as "1", even when I input an email that does not exist.
I've also tried returning
echo json_encode('true');
as I read somewhere that might work, but it did not help. Why is my response always wrong in my php?
The syntax of your remote rule is not correct:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
}
The way you've written it, the plugin is seeing async as just another rule. Since there is no such "rule" as async, the plugin will choke.
Following the documentation, try this:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php"
}
}
or this...
rules: {
......
email: {
required: true,
email: true,
remote: {
url: "check_email.php",
async: false
}
}
}
DEMO: http://jsfiddle.net/KkBSY/
My issue using the validation plugin is with the remote call specifically.
The remote checks to ensure the employee id is valid from the db. If it is valid then it returns a json string with the employee info (first name, last name, supervisor name, and facility name).
The issue is if I return that json string using the complete: function the empid field stays invalid with the error class, and will not allow the form to submit even though everything is valid. If I just return true from the remote call the empID field is valid and the form will submit (assuming the other fields are completed).
Is there a specific parameter in the json callback that needs to be set to true for the remote: call to finish and be true? I am lost as to how to fix this problem, so any help would be much appreciated! See below for the related code.
var ajax_data = new Object;
$('#vpnRequest').validate({
rules: {
empID: {
//required: true,
//minlength: 4,
remote: {
url: "checkEmpID.php",
dataFilter: function(data) { ajax_data = data; return data;},
complete: function() {
var jsonObj = new Object;
jsonObj = jQuery.parseJSON(ajax_data);
var success = jsonObj.status;
if(success == 'false'){
//return success;
}else if(success == 'true'){
$('#fName').val(jsonObj.fName);
$('#lName').val(jsonObj.lName);
$('#superName').val(jsonObj.supervisorFName+" "+jsonObj.supervisorLName);
$('#facilityName').val(jsonObj.facilityName);
$('#empID').addClass('stuff');
$('#empID').removeClass('stuff');
//return success;
}
}
}
}
},
messages: {
empID:{
required: "This field is required",
remote: "Invalid Employee ID"
}
}
});
PHP file empID checker:
$string[status] = 'true';
$string[fName] = ucwords(strtolower($row['empFirstName']));
$string[lName] = ucwords(strtolower($row['empLastName']));
$string[supervisorFName] = $superFName;
$string[supervisorLName] = $superLName;
$string[facilityName] = $facilityName;
}
$response = json_encode($string);
echo $response;
} else {
$response = json_encode($valid);
echo $response;
}
Adding to the validator code itself:
if ($.isFunction(param.validateResult)) response = param.validateResult(response);
from the site http://plugins.jquery.com/content/custom-function-handle-returned-data-remote-function appears to work extremely well, as it validates properly and submits the form. If anyone wants to test further to ensure fringe cases that would be great but this should definitely be added to the validator plugin to extend its capabilities.