My site is http://www.extrabux.com/users/login
When a user is logging in, Jquery Validate plugin uses a "remote" function to check whether the provided email address exists in our database as a user. If the connection and our server is fast, the user sees feedback before she even finishes typing her password.
email: {
required: true,
email: true,
remote: {//http://docs.jquery.com/Plugins/Validation/Methods/remote
url: 'check-signin-email-address',
type: "post",
data: {
emailAddress: function() {
return $("#email").val();
}
}
}
}
If the connection or our server is slow, however, this causes an undesirable delay before the form can be submitted (because the Jquery Validate plugin waits until the form is confirmed to be valid).
What I'd like is:
If the remote query finishes before the user submits the form, it should block the submission (in the case where it finds that the email address is not in the database).
If the user submits the form before the remote query finishes, the remote query validation rule should be ignored (so that there is no delay--the server-side validation will catch that the user doesn't exist).
Thoughts?
function checkEmail(){
$("#email").removeClass('email'); // this stops validation during ajax
//might want to add a loading image to let user know
$.ajax({
type: //type
url: //url to check email,
data: //email to check,
success: function (msg) {
$("#email").addClass('email'); //turns validation back on
//take away loading image
if (msg.GoodEmail != "GoodEmail" ) { //however you check for existing email
$("#email").addClass('error'); //forces failed validation
}
}
});
}
This is an example using jquery's ajax , with this you can handle events before ajax , on success , on error , a little more control this way
I think I figured this out. Instead of using the "remote" option, I used addMethod to create a rule that I call "isExtrabuxMember". I also created some global variables and used ajax bound to the change of the #email field to check whether the provided email address belonged to any existing Extrabux member.
Please comment if this helps you or if you have better ideas.
I now have this above the "validate" plugin call:
jQuery.validator.addMethod("isExtrabuxMember", function(value, element) {
var emailRemoteFuncResult = checkSigninEmailAddressResult === null ? true : checkSigninEmailAddressResult;
return emailRemoteFuncResult;
});
var checkSigninEmailAddressResult = null;
var emailXhrCheck;
$('#email').bind('change keyup', function(){
checkSigninEmailAddressResult = null;
if(emailXhrCheck){
emailXhrCheck.abort();
}
emailXhrCheck = $.ajax({
url: '/users/check-signin-email-address',
type: "post",
async: true,
data: {
emailAddress: function() {
return $("#email").val();
}
},
success: function(data){
checkSigninEmailAddressResult = data;
$("#email").valid();
}
});
});
$('#loginForm').submit(function(){
if(emailXhrCheck){
emailXhrCheck.abort();
}
});
Then within the "validate" plugin call:
rules: {
email: {
required: true,
email: true,
isExtrabuxMember: true
},
password: {
required: true,
minlength: 4
}
},
messages: {
email: {
isExtrabuxMember: function(){
var currentEmail = $('#email').val();
return $.validator.format('<b>{0}<\/b> does not yet have an Extrabux account. <a href="\/users\/register?emailAddress={0}">Sign up?<\/a>', currentEmail);
}
},
password: {
required: "Oops, you forgot to enter your password!"
}
}
Related
I need to check is session is still active on my client side. Are there any request possible which would not extend the session? I could use then this request to check if session is still active. Please provide suggestion I have no clue how to overcome this.
You can use setInterval function with ExtJS Ajax request to check active session that you specified time.
var checkSession = Ext.Ajax.request({
// the following url must response a value based on the
// user session status, long story short
// you should define a function in Grails
url: '/grails_url/function',
method: 'POST',
success: function (response) {
Ext.Msg.show({
title: 'Session Expired...',
msg: 'You session has been expired!',
width: 300,
height: 200,
closable: false,
buttons: Ext.Msg.INFO,
buttonText: { ok: 'OK'},
icon: Ext.Msg.INFO,
fn: function(btn) {
if (btn == 'ok') {
window.location.href = 'http://www.domain.com/login';
}
}
})
}
});
// check session for every 5 sec
setInterval(checkSession, 5000);
I've started using knockout js validations with http://ericmbarnard.github.com/Knockout-Validation/ validation engine, and I'm not clear as to how to do the following:
1) Say I want to set a particular field required based on a condition. How do I do that?
e.g.
this.Username = ko.observable().extend({ required: true }); // make required = true only if this.UserType = 2, etc...
2) I've got the validation messages firing right next to the field being validated. I want only an '*' to appear next to the field and display the error messages in a validationsummary field at the bottom of the page. All validation errors should display there. How to do that?
3) The form submit to be avoided until the form validation is passed. Rightnow, I get the validation error messages, still the form gets submitted. So I guess I'm doing something wrong. Following is my code:
$(document).ready(function () {
var model;
// enable validation
ko.validation.init();
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/GetData',
async: false,
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status) {
model = new ViewModel(result);
ko.applyBindings(model);
},
error: GetDataError
});
$('#submit').click(function () {
var data = ko.toJS(model);
delete data.Vehicles;
delete data.CopyWeeks;
delete data.SetupTotal;
delete data.CloseTotal;
var mappedItems = ko.utils.arrayMap(data.DailyItemList, function (item) {
delete item.Add;
delete item.Delete;
return item;
});
data.DailyItemList = mappedItems;
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/ProcessData',
async: false,
data: ko.toJSON(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, stat) {
alert(success);
return false;
},
error: function (e) {
alert(e);
}
});
});
});
Thanks in advance for your help.
EDIT:
I've seen that I can set the validation configuration as follows:
ko.validation.configure({
decorateElement : false,
errorMessageClass: 'errorMsg',
insertMessages : false,
parseInputAttributes : true,
messageTemplate: 'sErrorMsg'
});
ko.validation.init();
but I'm not sure how I can define my error message template 'sErrorMsg'
1). Say I want to set a particular field required based on a condition....
For this ko validation contains a native rule. You can do something like :
var myObj = ko.observable().extend({ required: {
onlyIf: function() {
//here you can place your codition and can return..
//true or false accordingly
}
}});
2). I've got the validation messages firing right next to the field being validated..
For this you should check Validation Binding. In this validationOptions can do the job for you.
Update: here's a fiddle which demonstrate the use of messageTemplate binding as per your requirement.
http://jsbin.com/ocizes/3/edit
3). The form submit to be avoided until the form validation is passed....
For this you can use use group , like :
yourViewModel.Errors = ko.validation.group(yourViewModel);
Now the Errors property contains the error messages of your observables, if any. So before submitting the form you can put check something like :
if(yourViewModel.Errors().length == 0) {
//submit the form
}
else {
yourViewModel.Errors.showAllMessages();
//this line shows all the errors if validation fails,
//but you can omit this.
}
When I call $("form").valid() I have a remote validation check hooked up (which all works well) however if all other fields are valid the form passes validation because the remote check hasn't return a response "quick enough".
Is there a way to either force jquery validation to wait for any remote checks to be completed or hook into the complete event of the remote check call?
I am currently using the remote validator built into the jQuery validation framework http://docs.jquery.com/Plugins/Validation/Methods/remote
one way is to introduce a variable that will be set to true when the remote call comes back
var remote_complete = false;
$.ajax({
url: "test.html",
success: function(){
remote_complete = true;
}
});
while (remote_complete == false)
{
// loop until remote_complete = true;
}
Another way is to validate your form after remote validation completes
$.ajax({
url: "test.html",
success: function(){
validate_form();
}
});
you can add a custom rule and in that custom rule you can make the ajax call.
Please check the SO post here for creating custom rules.
In that function make the ajax call.
Well, if you've setup all your rules correctly, then this shouldn't be a problem. See this demo where email is being validated remotely and the validation doesn't pass until the check comes back.
Can you post a jsfiddle that highlights your problem?
http://gloryplus.com/index.php?route=product/product&path=82&product_id=173
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
subject: {
minlength: 2,
required: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}
Why is the following validation function always failing. It even fails if I have both return case with true.
$.validator.addMethod("validate_old_password", function(value, element){
$.ajax({
url: '/users/ajaxPage_password_validation/',
type: 'POST',
dataType: 'text',
debug: true,
data: {
password: $("#id_old_password").val()
},
success: function(response){
if (response == "True") {
console.log('aa')
return true;
}// correct PW
return false; // bad PW
}
})
}, "password not valid");
I believe its because of the deferred execution.
When the "validate_old_password" method is called it simply kicks off the ajax call and continues to the end of the method, it won't wait around for the response.
You may want to consider using the remote validation options in the validation plugin.
Looking for some assistance with the Jquery form validation plugin if possible.
I am validating the email field of my form on blur by making an ajax call to my database, which checks if the text in the email field is currently in the database.
// Check email validity on Blur
$('#sEmail').blur(function(){
// Grab Email From Form
var itemValue = $('#sEmail').val();
// Serialise data for ajax processing
var emailData = {
sEmail: itemValue
}
// Do Ajax Call
$.getJSON('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc?method=getAdminUserEmail&returnFormat=json&queryformat=column', emailData, function(data){
if (data != false) {
var errorMessage = 'This email address has already been registered';
}
else {
var errorMessage = 'Good'
}
})
});
What I would like to do, is encorporate this call into the rules of my JQuery Validation Plugin...e.g
$("#setAdminUser").validate({
rules:{
sEmail: {
required: function(){
// Replicate my on blur ajax email call here
}
},
messages:{
sEmail: {
required: "this email already exists"
}
});
Wondering if there is anyway of achieving this? Many thanks
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Lets say we have a custom validation to check the Unique Mobile, So we will add a new method as follows to check the unqiue Mobile no :
jQuery.validator.addMethod("uniqueMobile", function(value, element) {
var response;
$.ajax({
type: "POST",
url: <YOUR SERVER SCRIPT/METHOD>,
data:"mobile="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else if(response == 1)
{
return false;
}
else if(response == 'logout')
{
return false;
}
}, "Mobile is Already Taken");
You can add a custom validation method like this
$.validator.addMethod('unique',
function(value) {
$.get('http://localhost:8501/ems/trunk/www/cfcs/admin_user_service.cfc','?method=getAdminUserEmail&returnFormat=json&queryformat=column&emailData='+ value,
function(return_data) {
return return_data;
})
}
, "this email already exists"
);
then add the unique class to your email field or you can use something like this
$.validator.addClassRules("unique-email", {
unique: true
});
Try this:
$.validator.addMethod('unique',
function(value) {
var result = $.ajax({
async:false,
url:"http://yoursamedomain.com/checkemail",
data:'email='+ value,
dataType:"text" });
if(result .responseText) return true; else return false;
} , "This email address has already been registered");
For serverside AJAX validation use remote rule. This is same as standard jQuery AJAX request object. Your server must returns string "true" for valid value or "false" for invalid, also it can passes some string "This email was already taken", and this will be perceived as invalid, and render as an error message:
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $( "#username" ).val();
}
}
}
}
}
});
Read documentation here remote-method