parsley.js prevents submit after failing ajax validation has been corrected - ajax

i have a form where i need to see if an email address entered into the form is already in a database. this check needs to be performed conditionally based on the value of another field in the form.
here is the form field:
<input type="email" value="" class="form-control" name="email_bill" id="email" required data-parsley-type="email" data-parsley-registered="1" data-parsley-trigger="focusout submit">
and here's the validator code:
Parsley.addValidator('registered', {
validateString: function(value) {
if ($('input[name="d_type"]:checked').val() == 'S') {
return $.ajax({
type: "POST",
url: "/is_registered.html",
data: $('form').serialize()
});
} else {
var parent = $('#email').closest('div');
var this_id = $('#email').attr('data-parsley-id');
$(parent).removeClass('has-error').addClass('parsley-success');
$(this_id).remove();
return true;
}
},
messages: {en: "Someone has already registered with the Email address you entered"}
});
the server code is trivial and returns a '200 OK' header if the address isn't in the database and a '404 Not Found' if it is. that works.
i followed the example in the parsley.js custom validator example for the simple ajax request.
what happens is: if i enter a 'registered' address, i get the appropriate error message. if i then go and modify that address to one i know is NOT registered and tab or mouse out to the next field, the error message goes away, BUT the submit button doesn't work. to further complicate the situation, if i load and fill out a form with a 'non-registered' address, the submit button doesn't work either. it appears that execution of the custom validator disables submit upon entry.
i've played with this for hours, trying all sorts of event manipulation, but nothing works.
i should point out that if the checked value of d_type (see field definition above) is NOT 'S', then everything works as expected.
i am totally baffled as to why following the documentation results in failure.

as it turns out, this was not a problem with parsley at all.
a colleague created the form and the submit button had an id of "submit' which could not allow parsley to resolve the submit handler. under those circumstances, apparently parsley blocks the submit.
who knew?
well now, we know.....

Related

Parsley remote validation is performed several times, even after successful submission

I am using Parsley in my project for form validation. One field in said form is an ID that must be unique - so I have added my own addAsyncValidator and on the backend I return 404 or 200 depending on whether an entry with the ID already exists or not.
When the form's submit button is pressed, I use
$("#frmobjectadd").submit(function(event){
$(this).parsley().whenValidate().done(function() {
//Ajax call to the backend to insert data here...
}
});
to deal with the async validation issues. Validation using this method works, however, I have noticed that pretty much every time I submit the form at least three Ajax calls are made for that field alone. Furthermore, when the form is valid, the data is sent to the backend where it is successfully processed. In the XHR log, I see an AJax response that indicates that it was successful, in which case I re-direct the user to a different page. Despite that, Parsley still sends a form validation request to the remote validator which fails since it is checking whether the entry I have just inserted already exists in the DB. This leads to an error message being displayed for a short amount of time before the re-direction takes place. Is there any way to fix this?
The remote validator:
Parsley.addAsyncValidator('objectexists', function (xhr) {
return xhr.status === 200;
}, "/backend/insert.php?formfunction=checkIfUnique&projectid=<?php echo $projectid; ?>");
The field in question
<input type="text" required
data-parsley-remote
data-parsley-remote-validator="objectexists"
data-parsley-remote-message="Object name already exists."
class="form-control" id="id" name="id" value="" placeholder="Type in object name">
Parsley initialization for the form looks like this:
$('#frmobjectadd').parsley({
errorClass: 'has-error',
classHandler: function(el) {
return el.$element.closest(".form-group");
},
errorsWrapper: '<span class="help-block"></span>',
errorTemplate: "<span></span>",
errorsContainer: function(el) {
return el.$element.closest('.form-group');
}
});
Why not let Parsley process the submit event, no need to call whenValidate either. Just listen to form:success or form:submit event instead.

MVC Custom Attribute - Client-side Validation - Warning: No message defined for 'field'

I tried to create a custom data annotation validation attribute (NameValidationAttribute) in MVC 5 project using VS2013. I was able to successfully add the client side validation and the error message for custom validation is getting displayed as soon as the focus leaves the textbox. However, the standard attributes like [Required] and [Range] validators are now not showing proper error messages, says 'Warning: No message defined for 'field' ' (See below screenshot).
Question:
- Why the standard validation error messages are showing as "Warning: No message defined for UnitsInStock"? What am I missing?
Below is my custom client validation script:
I included following scripts in EditProducts page.
Please note that the error messages for UnitPrice, UnitsInStock and ReorderLevel fields are defined with Range validation attribute (see below).
FYI, I tried to change the order of the scripts in ProductEdit page but still its showing the same message.
Please advise!
I ran into this issue. I had created an MVC attribute called PasswordAttribute, with a client side validator called 'password'.
$.validator.addMethod('password', function (value, element, params) {
...[validation logic]
});
$.validator.unobtrusive.adapters.addBool('password');
As soon as I added this logic to the solution I got the error you saw on my Password and ConfirmPassword fields. Note that this occurred before the attribute was even used. Simply renaming the client side validator to 'passwordcheck' fixed the issue. I initially thought that the name 'password' possibly clashed with one of the pre-defined validators (cf. jQuery Validation Documentation) but this doesn't appear to be the case. I suspect now that it is a clash with the name or value for some input field attribute. Anyway, the solution was simply to rename the validator.
jQuery unobtrusive need data-msg for default validate message.
This is how to apply dynamic error message from your model to Html
$.validator.unobtrusive.adapters.add("requireif", function (options) {
$('#' + options.element.id).attr("data-msg", options.message);
// Add rule ...
});
You can change default warning message.
$.validator.addMethod("requireif", function (value, element, pair) {
// validate logic
return true/false;
}, "YOUR DEFAULT MESSAGE HERE");
Or
#Html.TextBoxFor(m => m.Property1, new { Class = "form-control", data_msg = "YOUR DEFAULT MESSAGE HERE" })
Or if you can put it directly to your Html like this.
<input class="form-control" data-msg="YOUR DEFAULT MESSAGE HERE"/>

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

jQuery.validate stops my form from being submitted

jQuery.validate stops my form from being submitted. I would like it to just show the user what is wrong but allow them to submit anyway.
I am using the jquery.validate.unobtrusive library that comes with ASP MVC.
I use jquery.tmpl to dynamically create the form and then I use jquery.datalink to link the input fields to a json object on the page. So my document ready call looks something like this.
jQuery(function ($) {
// this allows be to rebind validation after the dynamic form has been created
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($("form"));
// submit the answers
$("form").submit(function(e) {
$("input[name=jsonResponse]").val(JSON.stringify(answerArray));
return true;
});
}
I note that there is an option
$("form").validate({ onsubmit: false });
but that seems to kill all validation.
So just to recap when my form is rendered I want to show all errors immediately but I don't want to prevent the submit from working.
So after some research (reading the source code) I found I needed to do 2 things
add the class cancel to my submit button
<input id="submitButton" type="submit" class="cancel" value="OK" />
This stops the validation running on submit.
To validate the form on load I just had to add this to my document ready function
$("form").valid();
Hope this helps someone else

How can I stop a form from processing/submitting that is using jquery AJAX submission?

I have a form with two buttons, a submit button and a cancel/close button. When the user clicks submit, the entered data is validated using http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/. If everything validates, the form is submitted with jQuery/AJAX. That all works fine and dandy. I run into problems with the cancel button though. I want the cancel button to require confirmation. If the user chooses to proceed, they are taken to a page of my choosing. If they decide they don't want to cancel, then they are simply left on the page. It's the last part that isn't working.
My form code looks like this:
<form name="createPage" id="createPage" method="post" action="pager.php" class="ajax updateForm">
<input name="whatever" type="text" />
<button type="submit" id="submitQuickSave" class="submitSave"><span>save</span></button>
<button type="submit" id="submitCancel" class="submitClose" onclick='confirm_close()'><span>close</span></button>
</form>
My current cancel script looks like the following. If the user does indeed want to cancel, I unbind the form submit so that validation isn't executed. The form then proceeds to submit and includes cancel as a parameter in the action attribute. I handle the cancellation server side and direct the user to a new page.
function confirm_close()
{
var r=confirm("All changes since your last save operation will be discarded.");
if (r==true)
{
$(".ajax").unbind("submit");
}
else
{
}
}
I cannot figure out what to put in the 'else' argument. What happens is that if the users cancels the cancellation (i.e., return false), then the form still tries to submit. I cannot make it stop. I've tried several things from this site and others without success:
event.stopImmediatePropogation
.abort()
Any ideas? Basically, how can I get the cancel/close button work properly?
Consider separating your JavaScript from your HTML. With this in mind, you could write the handler for your the click event you're trying to intercept like this:
$("button#cancel").click(function($event) {
var r = confirm("All changes since your last save operation will be discarded.");
if (r) {
$(".ajax").unbind("submit");
}
else {
$event.preventDefault();
}
});
You would have to tweak your HTML and add an id attribute to the cancel button:
<button id="cancel" type="submit" value="cancel">Cancel</button>
Example here: http://jsfiddle.net/wvFDy/
Hope that helps!
I believe you just
return false;
Let me know if this works.

Resources