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...
Related
I have a problem, I validate my form with js plugin Parsley , and on pages where Parsely plugin is initiated the form input type="file" is not working, not clickable" , is see the button animates when clicked but no pop up for the file-system to pick file for upload, and the input is not validated by parserly , inputs on ALL the page where there is Parsly do not work, when I comment out the Parsley instantiation the file input works as expected, here is how I init the plugin:
app.Manage.BasicInfoForm.parsley(app.Manage.validatorConfig).validate();
before this line is executed the inputs work fine also if I have custom validators declared it will prevent file input from working as well like:
window.Parsley.addValidator('reservednamescheck',
function (value, requirement) {
var noAllow = app.websiteManage.noAllowWebsiteNames;
var forbbidenName = '';
for (var i = noAllow.length - 1; i >= 0; i--) {
if (value === noAllow[i]) {
forbbidenName = noAllow[i];
return false;
}
}
return true;
}, 32)
.addMessage('en', 'reservednamescheck', 'Sorry but this name is reserved');
so this will prevent file input from working as well, again, even if file input is standalone anywhere on the page it does not work when Parsley is present, Please help, Thank You
my bad, the problem was not with the plugin but with an jquery event , this code was causing the problem:
$(document).on('click input ', app.websiteManage.websiteNameInput , function(event) {
event.preventDefault();
// detects if inputed website name accordingly changes the title
app.websiteManage.websiteNameBind.html(app.websiteManage.websiteNameInput.val());
});
so I was listening to click and preventing the default behavior , that is why my input file was not working, thank You for everyone who tried to help ;)
Check your version number. The API has changed, and in the 2.0+ version, the 3rd parameter is the parsley instance.
So you would add the message inside your function, something like:
window.Parsley.addValidator('myvalidator', {
requirementType: 'string',
validateMultiple: function(value, dataProp, instance) {
.
.
.
instance.reset(); // clear previous error
instance.addError('en', {message: 'my message here'});
return false;
},
messages: {
en: '...'
}
})
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
i have a multi-page form that i am trying to validate using jquery validate. the user has essentially 4 options: next, prev, save, submit.
save, next, and prev all save the current page to the form as a whole; submit is the same as save, but fires some additional workflow-related functions then heads off to another part of the site.
i need to validate the user input at all times. the jquery validate is working great. but... i need to have some fields set as required. because the form is saved at each step, the input needs to always be valid, but i don't need the required validation until the very end (on submit).
the form is building a dynamic list of validations specific to the page it is on, like:
$(document).ready(function() {
$("#ctl01").validate({ onsubmit: false });
$("#_Qn_0e868ebe").rules("add", { maxlength: 200 });
$("#_Qn_d69e75a4").rules("add", { number: true });
$("#_Qn_adffbdec").rules("add", { maxlength: 200 });
$("#_Qn_adffbdec").rules("add", { digits: true });
});
so now, for required fields, i've added a .isrequired class to them, and i've decoupled the <asp:linkbutton>s to fire this client script:
function FormIsValid(sender, ishardsubmit) {
var form = $("#ctl01");
form.validate();
if (form.valid()) {
//if (ishardsubmit) {
// if (!IsRequiredValid()) { return false; }
//}
__doPostBack(sender, '');
}
return;
}
this part (the input validation part) is working great so far. the part i commented out is the part that is working not so great. it fires this function, in which i was trying to dynamically add required validators and re-evaluate the form. i can see it hit the .each loop for each of my required fields, but it doesn't seem to be working since it passes true back, even when required fields are empty.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function (i, item) {
$(item).rules("add", { required: true });
});
form.validate();
return form.valid();
}
i toyed with the idea of dropping the .net required field validators in to do this part, but i want to, if possible, stick with a single solution. especially since this feels so close to working.
thoughts? help? thanks!
Your jQuery .each() method is constructed improperly.
You want to target the whole object in your iteration, not key/value pairs. So remove i, item from the function arguments and use $(this) as the target selector.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function() {
$(this).rules("add", { required: true });
});
// form.validate(); // remove this line -> 100% superfluous
return form.valid();
}
Regarding your form.validate() line in both functions: You cannot call .validate() more than once on the page. It's only meant to be called once to initialize the plugin on your form.
Calling it subsequent times will have no effect. Otherwise, we wouldn't need to use the .rules() method as we would simply call .validate() any time we need to change rules. However, this is definitely not the case.
Add a class to your required fields called something like: "SubmitRequired"
Implement two functions as follows:
function SaveClick(){
//ignore SubmitRequired on save (and any disabled fields)
$("form").validate({ ignore: ".SubmitRequired, [disabled]" });
if $("form").valid()
{
do something;
}
}
function SubmitClick(){
//ignore only disabled fields (if any))
$("form").validate({ ignore: "[disabled]" });
if $("form").valid()
{
do something;
}
}
I have very basic knowledge about JS/jQuery. I need to perform check on the value of certain text boxes. The example just recreates the problem I heave with the real application which is a lot bigger and the tables are dynamically created based on a data from a data base, so in run time I add the classes on which I base my jQuery logic.
Here is the jsfiddle example - http://jsfiddle.net/Xhnbm/
There are three different checks I need to do - for float, for string length and for float, however you may see that the validations is not performed I always get the integer exception and even if you remove the integer check the validation is not working either, so I guess the problem is not in the functions themselves but somewhere else.
Thanks for help.
P.S
It seem I can't submit the question without adding code. All the code is in the jsfiddle example but since I need to add some here too, I think that the problem is either in the way I declare may functions that perform the check or here :
$('#submitDocument').click(function () {
try {
if ($(".checkString16").val().length > 16) {
throw "The text can be up to 16 symbols";
} else if (!mathFunctions.isInt($(".checkULong").val())) {
throw "Insert integer";
} else if (!mathFunctions.isFloat($(".checkFloat").val())) {
throw "Insert float";
}
validationResult = true;
} catch (exc) {
alert(exc)
validationResult = false;
}
return validationResult;
});
in the way I try to execute the validation when the submit button is clicked. But being no Js programmer at all I don't want to point you to wrong directions.
$('#submitDocument').click(function () {
var validationResult = true;
if ($(".checkString16 input[type='text']:first").val().length > 16) {
validationResult=false;
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
validationResult=false;
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
validationResult=false;
}
return validationResult;
});
This should do the trick.
If the #submitDocument is a input type='submit' and you use it to submit the form, you should try this way:
$('#submitDocument').click(function (e) {
if ($(".checkString16 input[type='text']:first").val().length > 16) {
e.preventDefault();
} else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
e.preventDefault();
} else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
e.preventDefault();
}
});
The e.preventDefault() will prevent the submit button from doing it default handler, which is submitting the form.
You can always submit the form manually from the code, using $("#formId").submit();
PS. Make sure that you are also validating those values in code behind, because simple jquery validation is easy to come around.
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.