How do I show what validation errors Parsley.js has found? - javascript

I'm using Parsley.js to validate part of a form like in this example. However, the validate() method always returns false, even when that piece of form should validate.
No error messages are displaying, and I want to see what it is that's failed validation.
I can't see a way to get Parsley to simply return all the errors found, so I can see them in the console. Have I missed something obvious?

You can use something like this:
window.Parsley.on('field:error', function() {
// This global callback will be called for any field that fails validation.
console.log('Validation failed for: ', this.$element);
});
from http://parsleyjs.org/doc/index.html#events

There are probably (hopefully) better ways to do this, but this kind of thing is what I ended up using to get some insight into what's being validated and what is/isn't passing:
function validateAnswers(groupName) {
var formInstance = $('.my-form').parsley();
var isValid = formInstance.validate(groupName);
// Just for debugging:
$.each(formInstance.fields, function(idx, field) {
if (typeof field.validationResult === 'boolean') {
// Validated.
console.log('Passed: ' + field.value);
} else if (field.validationResult.length > 0) {
console.log('Failed: ' + field.validationResult[0].assert.name);
}
});
return isValid;
}
This worked on my very simple form with 'required' radio buttons; no idea how it would work on larger forms with different types of fields and validation requirements.
Any better answers or improvements?

Here's what I did for this type of situation.
var formElements = $('form .elementClass').parsley(); // Get all elements inside your form
// Loop through all the elements found
_.forEach(formElements, function(formElement) { //You can use a regular for loop if you prefer
var errors = ParsleyUI.getErrorsMessages(formElement); //Get the list of errors for this element
if (errors.length) {
// Output the first error in the array. You could loop this too.
console.log(errors[0]);
}
});
It feels a bit ugly, but it gets you what you need.

Related

Compare duplicate values of two select in materializecss framework

I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime

How to know which field is invalid in knockout validation?

I have a rather big knockout model and I want to validate all nested models in it:
self.errors = ko.validation.group(self, { deep: true });
Validator found an error:
> self.errors()
["This field is required."]
I don't know which field of my huge model is invalid. How can I find out it?
I guess you should be looking for something like this
// Getting errors
var errors = ko.validation.group(this, {
deep: true,
observable: false
});
// New method: getting extended details
var details = errors.getDetails();
for (var i = 0; i < details.length; i++) {
var d = details[i];
/*
Every element contains the following fields:
"observable" - a reference to the target observable.
"error" - the error message.
"rule" - the name of the failed validation rule.
"data" - an object that contains extension data (provided via "extend" method) for every rule. E.g. "data.required == true".
*/
}
PS: You need to add few lines in your validation file to make getDetails() work i.e which may not be there in validation script file you have .(check reference link & check code)
Reference Here and credits to volpav it helped me long back .
Just incase if someone looking for working sample check here

jQuery with remote validation does not wait for answer from server

I've noticed, that sometimes my validation code works wrong:
var $validator = $("#checkoutForm").validate();
...
if (!$validator.element($sameShippingAddress)) {
...
}
Debugging with Firebug showed, that sometimes $validator.element($sameShippingAddress) would return undefined (I guess it just does not wait till response is returned) and that would be assumed as false, even if element is valid.
If add code like this before if statement, everything works fine:
while (validator.element($sameShippingAddress) !== undefined) {
}
Question is if that is right solution and there's no better way to handle problem with validation plugin itself?
Update: I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Infinite while loop on validator variable is not a good choice. Instead use the code below that utilise Javascript timer. You can show animated processing/server response graphics after validate() method.
var validator = $('#resetpassword').validate({///your code...})
doTimer();
function timedCount()
{
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (validator === undefined)
{
timedCount();
}
}
if(validator==true)
$('#form').ajaxSubmit(options);
It's hard to tell how you are handling successful submissions or if you uses the css class to denoted required fields, but the following is how it's done in the demo for the plugin:
$.validator.setDefaults({
// code to be executed on submit
submitHandler: function() { alert("submitted, replace this with your server request");}
});
$().ready(function() {
// validate the comment form when it is submitted
// use css class .required for fields you want the validator to check
// if your form is valid then it is handled by the submitHandler
// if not the plugin displays error messages
$("#checkoutForm").validate();
//validate can take a block for custom validation and error messages
});
Hope this helps you find a solution and isn't just more of the same (also just realized this question is a year old, but I already wrote this so...)
Obiously, it is not the best solution. Instead add
if (!$validator.element($sameShippingAddress)) {
...
}
in the Ajax callback function.

jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...

Jquery Custom Validate Plugin AddMethod on Dynamic Forms

I am trying to use the Jquery Validate Plugin and I was able to figure out how to use it on static fields.
My problem is on how to used it on my dynamic forms. I created a fiddle to discuss my problem. Hope you can have patience on reading this. The fiddle link is here
Now, here's what I want to do, validate the Machine ID entered on each text box and make sure that it is unique. Say you enter ABCD-123 twice, the system should alert you that it is not unique.
Hoping somebody could lend me a hand on this. Thanks
first of all - put comments in your code while you write.
the error is here:
var arrElements = $(".machineID");
arrElements is always empty, there is no element with machineID class
and your each doesn't work. I refactored it http://jsfiddle.net/PaTJ4/
Your code could use some more fixes, it's a bit too complicated for that task. But now it works.
good luck
I've improved on your version - when a duplication is detected, any one of the duplicated fields should be marked as invalid, and should be able to be changed in order to fix the problem. So, you'd need to revalidate all other fields every time (using validator.element()), but avoid a recursion (using validator.validatingOthers).
I'll post the code for checkMachineIDs here for completeness:
function checkMachineIDs(element){
if($(element).val() != ""){
var arrElements = $("#machineList .machineID");
var $element = $(element);
var validator = $($element[0].form).validate();
if(arrElements.length > 1){
var valid = true;
arrElements.not('#'+$element.attr('id')).each(function() {
var current = $(this);
if (current.val() == $element.val())
valid = false;
});
if (!validator.validatingOthers) {
validator.validatingOthers = true;
arrElements.not('#'+$element.attr('id')).each(function() {
validator.element(this);
});
if (valid) validator.element($element);
validator.validatingOthers = false;
}
return valid;
}else{
return true;
}
}else{
return true;
}
}

Categories