I need to validate an email field using the jQuery.Validate() plugin it has a "Remote" method which we have to post to a server and server needs to return true or false, Instead of using the traditional way(adding a function on the server to return true or false), I need to get json response from the server and on success run a function to decide where to return true or false...
Here is what the response from the server looks like (I'm using the Yii ajax form validation)
{
"zipcode":[
"Zipcode cannot be blank."
],
"email":[
"Email is already registered"
],
}
If email is listed on the array that means the validation had errors So I create a Remote validation rule like follows:
'email': {
required: true,
email: true,
remote:{
type:"POST",
url:url,
dataType:'json',
data:{'email':function(){
$('#email').val();
},ajax:'validate'},
success:function(resp){
$.each(resp,function(index,value){
if(index == "email")
return false;
});
}
}
},
But does not work, also I did not found anywhere where I can add the error message for remote validation, I would like to pass the array email value as the message...
You need to replace your success function with below function :
dataFilter: function (data) {
return 'false'; //Email not exist
return 'true'; //Email already exist
}
Please pass true/false value as a string.
For Display Message :
remote:{......},
messages:{email:'Please enter valid email', remote : "{0} is already exist"}
I think this will be help.
Related
I am trying to validate an html function with django and the JavaScript FormValidation plugin. I want validation
to check if the inserted email already exists,
This is my validation remote
email: {
validators: {
notEmpty: {
message: 'email field can not be empty'
},
emailAddress: {
message: 'is not a valid email'
},
remote: {
message: 'email is already in use',
url: '/validate_email/',
type: 'post',
data: {
email: function() {
return $('#email').val();
}
},
},
},
},
The url calls to my view def which is
def validate_email(request):
email = request.GET.get('email', None)
data = not Vendors.objects.filter(email__iexact=email).exists()
if data is True:
data = "true"
else:
data = "false"
return JsonResponse(data, safe=False)
I am getting a correct "true" or "false" JsonResponse, but the message always shows that the email is already in use and keep asking me to correct it.
I tried passing the JsonResponse as true or false without "", also tried passing the JsonResponse as is_taken: true or is_taken: false.
In your Django view, you need to return a JSON response in the following format:
return JsonResponse({"valid": data})
The FormValidation plugin will understand that the email is valid if the response is "valid":true and invalid if the response is "valid": false.
I want to send to the controller a new e-mail given by the user using ajax
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: function() {
return $('#email').val();
}
},
success: function(result) {
console.log('function');
if(result === true) {
console.log("true");
} else {
console.log("false");
}
}
});
To the controller (sample code)
#PutMapping("/changeEmail")
public boolean changeEmail(
#RequestParam("email") String email
) {
System.out.println("email: " + email);
return true;
}
However, when dispatching, the browser console throws me out
jquery-3.2.1.min.js:4 PUT http://localhost:8080/signIn net::ERR_TOO_MANY_REDIRECTS
Ajax is trying to send data to a completely different address than the one I provided in ajax.
In Ajax I gave
/changeEmail
And he is trying to send me on
/signIn
What this is about?
A couple of issues here. Firstly remove the ? from the end of the URL. jQuery will add it automatically, if required.
Secondly don't provide a function in the object you set to data. Give the value directly. Also, result will be a string, so your comparison to a boolean will not work as you expect. To be safe while testing, it's best to just log the response directly. Try this:
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: $('#email').val();
},
success: function(result) {
console.log(result);
}
});
Lastly, if your request is being redirected from /changeEmail to /signIn, then it sounds like you will need to authenticate the request. Exactly how you do that varies from one API to another, so I'd suggest you check their documentation.
First I don't have much experience with javascript and jquery :) I am just trying to find a quick way to connect jquery email validator module with a function that checks recaptcha. Here is my code:
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
Works fine! Inputs are validated.
Now after validation I need two things: First I need to call recapVerify(), after recaptcha gets validated I need to submit my form. This is the example I use: email method. I know I need to use submitHandler now but I can't figure out where and how?
Btw. this is recapVerify() function that I want to use:
function recapVerify(){
$.ajax({
type:'post',
url: 'captcha_check.php',
data: {
recaptcha_challenge_field:$('#recaptcha_challenge_field').val(),
recaptcha_response_field:$('#recaptcha_response_field').val()
}
}).done(function(data, textStatus, jqXHR){
if (data == 'success'){
$('#err').addClass('hidden');
//document.forms[0].submit(); // uncomment this line to submit your form
alert('Success, the form and reCAPTCHA validated, your form was submitted');
} else {
$('#err').removeClass('hidden');
}
}).fail(function(jqXHR,textStatus,errorThrown){
console.log('recaptcha or service failure');
});
}
use submitHandler on your jquery validate function. Debug is not needed. In essence this is the javascript you need.
$(document).ready(function(){
$("#test-form").validate({
rules: {
name: {
required: true,
},
email : {
required : true,
email : true
}
},
submitHandler : recaptchaVerify
});
});
function recaptchaVerify(form){
console.log(form);
alert("in submit handler");
}
According to the documents at jQuery validate
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it is validated.
Have also created a fiddle so that you can use it.
I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.
I'm coming into the middle of this project so I'm having to do a bit of re-writing because of sloppy code. I am using jQuery 1.6.1 and Validate 1.8.1.
First, here's the PHP which runs the back-end (dbquery.php):
include("../includes/dbconnection.php");
session_start();
$location='';
$action='';
if($_GET['action']=='')
$action=$_POST['action'];
else
$action=$_GET['action'];
if($action=='checkusername'){
$error='';
$username=$_GET['username'];
// exclude denied account
$checkuserquery=mysql_query("Select * from database_users as user LEFT OUTER JOIN database_approval as approval on user.user_id=approval.approval_user_id where (approval.approval_status IS NULL or approval.approval_status <> 4) and user_username='".$username."'");
$checkuserresult=mysql_numrows($checkuserquery);
if($checkuserresult>0) {
$error = 'false';
} else {
$error = 'true';
}
echo $error;
}
I'm trying to use jQuery Validate script to query the database for existing usernames on the fly. I either get two extremes: it never works or it always spits back given username as taken.
I believe the problem is that I cannot grab the input value of the username variable. When I create alert (username) within function (output), it returns nothing. My assumption is that .val() is only working when the page loads thus anything I'm typing into the input isn't working for some reason.
Here's the jQuery I've re-written and copied from sources online:
$(document).ready(function(){
$.validator.addMethod("checkAvailability",function(value,element){
var username = $("#username").val();
$.ajax({
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function(output) {
return output;
}
});
},"Sorry, this user name is not available");
// jQuery Validation script
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
checkAvailability: true // remote check for duplicate username
},
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
I am only a beginner with jQuery but am getting my hands pretty dirty with this code. Am I on the right track or should I use remote: under rules and username? I've been told that the remote method won't work because of the dynamnic nature of the input value I'm trying to validate.
The other major problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
The original coder was referencing getXMLHTTP and using ActiveXObject. The method he programmed seemed a little outdated so I'm trying to make the code a little more contemporary and clean it up.
5/25 - I am editing this to include the OLD original JavaScript code which works but is using the outdated method which I'd like to get away from (I have since removed the following code and replaced with jQuery above):
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
//validate username
function validateUsername(username){
var strURL="dbquery.php?action=checkusername&username="+username;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
if(req.responseText=='notavailable'){
document.getElementById("errorusername").style.display="block";
document.getElementById("errorusername").innerHTML="<div id=\"errors\"><strong>"+username+"</strong> is already taken by another user.</div>";
error = true;
}
else{
error = false;
document.getElementById("errorusername").style.display="none";
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
Check when the validation function is getting called, what the value of username is and what the value of output is: is it true or "true"?
I'm guessing latter: a string, so you could just do:
return output === "true" ? true : false; // I sincerely recommend using === here
Since if you return "false"; will evaluate to true because it's a non-empty string - yay dynamic langauges! :/
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
While you adding addMethod you should return true or false from server side.
and also that value have to be returned from addMethod.
ie something like this
$.validator.addMethod("checkAvailability",function(value,element){
var parameter="action=checkusername&username="+username;
$.ajax({
url: "dbquery.php",
type: "POST",
async: false,
data: parameter
success:function(output)
{
return output
}
});
},"Sorry, this user name is not available");
I faced the same problem, But I find the easiest solution just return true or false after encoding into json through php.
if ($users->username_exists())
{
echo json_encode(FALSE);
}else{
echo json_encode(TRUE);
}
On your server side script, try returning true or false instead of available and notavailable, as both of those strings are equivalent to true.
My code:
$( "#myform" ).validate({
rules: {
EMAIL: {
remote: {
type: "post",
url: "checkMail.php",
data:{checkUsername:function(){return $("#EMAIL").val()}
}
}
}
},messages:{EMAIL:{remote: "Already taken!"}}
});