jquery validation - waiting for remote check to complete - validation

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');
}

Related

calling laravel route in javascript

Can you call a laravel route in javascript?
I am trying to implement a front-end validation with jquery validate plugin. The reason that I am doing a front-end validation instead of the validation function provided by laravel is that I am using a bootstrap modal for my login form and I do not want the user to dismiss the form upon clicking the "submit" button.
Currently I am doing something like this:
$("#modal-form-login").validate({
errorClass: "error",
errorPlacement: function(error, element) {
error.insertAfter(element.parent("div"));
},
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 4
}
},
messages: {
email: {
required: "メールアドレスが必要です",
email: "有効なメールアドレスを入力してください"
},
password: {
required: "パスワードが必要です",
minlength: jQuery.format("少なくとも {0} 文字")
}
},
submitHandler: function(form) {
$.ajax("http://mywebsite.com/login",{
dataType: 'json',
data: $('#modal-form-login').serialize(),
success: function(response) {
console.log("ok!");
}
});
}
});
I understand that the post-validation handling should be in submithandler, and I want to call my doLogin route (which is reachable via {{ URL: to("doLogin") }} in blade), but can I achieve this in javascript?
You don't want to be making php calls in your javascript. For that to work, your javascript file would have to be served by php. Your JS and CSS files should be static and should not be served by php. So the question you should be asking is "How do I inject values into javascript?" I like to pull urls out of the dom.
I'd set my login form to look something like this:
<form id="modal-form-login" method="post" action="{{ URL::to("doLogin") }}">
Then I'd update my submit handler to look like this:
submitHandler: function(form) {
$.ajax($('#modal-form-login').attr('action'), {
dataType: 'json',
data: $('#modal-form-login').serialize(),
success: function(response) {
console.log("ok!");
}
});
}
As you can see here, I'm pulling the url from the action of the form.
There are a few packages that exist for using Laravel named routes in JS.
I personally maintain Ziggy and I've also heard good things about Laroute

how to? with knockout js validations

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.
}

How to abort remote Jquery Validator method upon submit

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!"
}
}

MVC 3 Client side validation on jQuery dialog

I am showing lots of form using jquery dialog and I wish to add in client side validation on it. I read through some examples, saying that mvc 3 already somehow support jquery client side validation, but I tried by including the necessary script, and my form like this:
#using (Html.BeginForm("CreateFood", "Home", FormMethod.Post, new { id = "formData" }))
{
#Html.ValidationSummary(false, "Please fix these errors.")
When i try to submit my form without fill in the required field, I still dint get any message. Can anyone give me more idea / explanation / examples on this??
Really needs help here... Thanks...
UPDATE (add in the script for my dialog)
$createdialog.dialog("option", "buttons", {
"Cancel": function () {
//alert('Cancel');
$createdialog.dialog('close');
},
"Submit": function () {
var frm = $('#formData');
$.ajax({
url: '/Food/CreateFood',
type: 'POST',
data: frm.serialize(),
success: $createdialog.dialog('close')
});
}
});
Once dropped, open dialog:
// Once drop, open dialog to create food
options.drop = function (event, ui) {
// Get the ContainerImgName which food dropped at
var cimg = $(this).attr('id');
// Pass in ContainerImgName to retrieve respective ContainerID
// Once success, set the container hidden field value in the FoodForm
$.ajax({
url: '/food/getcontainerid',
type: 'GET',
data: { cImg: cimg },
success: function (result) { $('#containerID').val(result); }
});
clear();
$.validator.unobtrusive.parse($createdialog);
$createdialog.dialog('open');
};
I've faced the same problem, solved with:
$(name).dialog({
autoOpen: true,
width: options.witdth,
heigth: options.height,
resizable: true,
draggable: true,
title: options.title,
modal: true,
open: function (event, ui) {
// Enable validation for unobtrusive stuffs
$(this).load(options.url, function () {
var $jQval = $.validator;
$jQval.unobtrusive.parse($(this));
});
}
});
of course you can add the validation on the close event of the dialog, depends on what you're doing, in my case the popup was just for displaying errors so I've performed validation on load of the content. (this pop up is displaying am Action result)
For every dynamically generated form you need to manually run the validator once you inject this content into the DOM as shown in this blog post using the $.validator.unobtrusive.parse function.

jquery validation always fails

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.

Resources