improve my jquery validation plugin code - javascript

Just hoping soemone can help me to write better code than I can come up with on my own.
I am using the jquery validation plugin. I have some fields that are mandatory ONLY if certain options are chosen.
The below code works fine. But the thing is, is that that my list of 'OR's is much longer than I've put here. and it needs to be applied not just to 'directorsName' but a whole long list of inputs, selects etc.
My question is.. how can I wrap up the code contained inside the RETURN?
(so I dont have to keep repeating my 'OR's. I'm guessign I need a function but I'm unsure of the syntax)
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return ( $('#account_for').val() == "Joint" || $('#directors_number').val() == "2" || $('#directors_number').val() == "3" );
}
}
}
});
Thanks in advance

Here's a code snippet for a custom validator. You can apply this same syntax to your own custom validation needs.
$.validator.addMethod("noanon", function(value) {
return value.toLowerCase().indexOf("anonymous") != 0;
}, 'Do not hide behind the cover of anonymity')
You can then use it just like any of the built-in validation rules like:
name: {
required: true,
minlength: 2,
noanon: true
},
If you have not already read it, I suggest reading the 3-part blog that this code comes from over at coldFusion Jedi.

You can do this, which is supported cross browser using $.inArray():
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return $('#account_for').val() == "Joint" ||
$.inArray($('#directors_number').val(), ['2','3']);
}
}
}
});

list = ['1', '2', '3', '...'];
return $('#account_for').val() == "Joint" || list.indexOf($('#directors_number').val()) != -1;

Related

How to handle two forms on one page for validation?

I have two forms that get displayed alternatively in a popup, one for editing (which is loaded by ajax), one for creation.
I want to use jquery validation to display hints both on editing and on submission of fields.
Some of the validation involves time spans which must not overlap.
This works for creation, but the new rule I am creating for editing does not get triggered because the rule for creation takes precedence.
I have added class rules, because the rules I created by name or id somehow don't get active at all, maybe because I am confused how the jquery validate plugin works. These rules are commented out in the code snippet.
var classRules = {};
classRules['thresholdStartTime'] = {};
classRules['thresholdStartTime'][globalThresholdCheckName] = $form
classRules['thresholdEndTime'] = {};
classRules['thresholdEndTime'][globalThresholdCheckName] = $form
/*
*
for(var q = 0; q<20; ++q) {
validationrules['thresholdStartTime' + q] = {};
validationrules['thresholdStartTime' + q]['required'] = true;
validationrules['thresholdStartTime' + q][globalThresholdCheckName] = $form
validationrules['thresholdEndTime' + q] = {};
validationrules['thresholdEndTime' + q]['required'] = true;
validationrules['thresholdEndTime' + q][globalThresholdCheckName] = $form
}
*/
for(var cls in classRules) {
var rule = classRules[cls];
$.validator.addClassRules(cls, rule);
}
//return validationrules as rm.rules here
//in the caller, get validationrules from result
var editForm = $('#editForm')
.validate(
{
rules : rm.rules,
classRules: rm.classRules,
messages : rm.messages,
success : $.noop
});
Make the form's default action be prevent e.preventDefault(), then submit using jQuery.ajax(), choosing what data to send, then bind that ajax request to the form's submit button. Do this for each form:
jQuery('.bidvalue').click(function(e) {
e.preventDefault();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: 'action=newbid&id='+e.target.name,
success: function(msg){
jQuery('#vehicle-value-box'+e.target.name).html(msg+',00€');
}
});
EDIT, as I completely missed the actual question...
For each form, you can specify validation as below:
$('#myform1').validate({
rules: {
myfield1: {
required: true,
minlength: 3
},
myfield2: {
required: true,
email: true
}
}
});
but you'll have to be more specific and show the HTML of both forms, and maybe what validation rules you'd like, for me to really answer your question helpfully.
EDIT #2: To add some stuff form the comments (kudos to Vicente Olivert Riera for input).
If you wish to toggle which form to apply validation upon, do this:
var activeForm;
$("form").focus(e => {
e.validate({
rules: {
myfield1: {
required: true,
minlength: 3
},
myfield2: {
required: true,
email: true
}
}
});
});
If you have many forms and just want specific forms matching certain criteria only:
$("form").focus(e => {
// Some criteria to check against for the form.
// Obviously you could make a crafty selector and avoid `if (e.hasClass())`,
// but this is to demonstrate using if to test the form if you wanted to check the form element in any way before applying `.validate()`.
if (e.hasClass("someClass") {
e.validate(...);
}
});

how to disable typeahead:active when focusing a filled-in text field in a remote typeahead.js

I'm using typeahead.js and it's great but here's my use case: I have a text field that is already filled in with a string on the server side when the page is loaded, so I don't want the suggestions menu to be shown when the user focuses the text field.
typeahead.js seems to always show the menu when focusing the text field. This makes sense since minLength is 2 and the text field value is something like "Tony" (or whatever). But I've tried using hint: false and calling $('.typeahead').typeahead('close') inside a callback for the typeahead:active event, and neither seem to stop the menu from being shown.
Here's the init code I'm using:
$('#locationInput').typeahead({
hint: false,
highlight: false,
minLength: 2
},
{
name: 'locations',
display: 'name',
source: typeaheadLocations, // a simple Bloodhound instance
templates: {
suggestion: function(locationObj) {
return $('<div>' + locationObj.name + '</div>');
}
}
});
There is a slight delay between when I focus the text field and the menu is actually shown, because the remote GET has to be run. So I'm guessing I would need to prevent that somehow, after it's focused.
Looks like closing the menu in the typeahead:open event does the trick, but this seems pretty hack-ish to me. :(
$('#locationInput').typeahead({
hint: true,
highlight: true,
minLength: 2
},
{
name: 'locations',
display: 'name',
source: typeaheadLocations,
templates: {
suggestion: function suggestion(locationObj) {
return $('<div>' + locationObj.name + '</div>');
}
}
}).on('typeahead:open', function(e) {
var $input = $(e.currentTarget);
if (!$input.data('wasFocusedOnce')) {
$input.data('wasFocusedOnce', true);
$input.typeahead('close');
}
}).on('typeahead:close', function(e) {
$(e.currentTarget).removeData('wasFocusedOnce');
}).on('keydown', function(e) {
$(e.currentTarget).data('wasFocusedOnce', true);
});
If anyone knows of a better way to do this, I'm all ears!

Clean previous JQuery validation error message

I have two validations for the same field and I´m using jQuery Validator, I would like to know how to clean the previous error message generated.
My problem now is that If I have the error for empty field, never is removed if I have another error like value must be higher than 10. I still showing "field must not be empty" when the value is 7.
I google on that and all suggestion are resetForm of validation.
var validator = $("#myform").validate(
);
validator.resetForm();
But of course if I do that the error message wont be showed. I just need to clean the previous error from the DOM before check for news.
Anyone knows another approach directly interacting with the DOM?
I´m trying this without success.
if ($.validator.defaults.onfocusout) {
$(element).unbind(".validate-biggerThanOrigin").bind("blur.validate-biggerThanOrigin", function () {
$(element).valid();
});
}
We´re defining the validation like this.
$.validator.addMethod("biggerThanOrigin", function (value, element, param) {
return biggerThanOrigin(value, element, param, validationMessages.biggerThanOrigin, validationMessages.referenceForkEmpty);
});
$.validator.addMethod("lessThanOrigin", function (value, element, param) {
return lessThanOrigin(value, element, param, validationMessages.lessThanOrigin, validationMessages.referenceForkEmpty);
});
Regards.
You should provide separate validation messages for errors.
$("#myform").validate({
rules: {
name: {
"required": true,
"minlength": 10
},
messages: {
name: {
required: "Please specify your name",
minlength: "Your name must be atleast 10 characters long"
}
}
});
This should work in your case.
EDIT:
Here is a working FIDDLE.
As you asked another approach , so here is the solution.
FIDDLE:
$('input').on('keyup', function () {
if ($(this).val().length == 0)
$('label').text('Field must not be empty');
else if ($(this).val() <= 10)
$('label').text('Value must be greater than 10');
else
$('label').text('');
});
This is just an example. You can use the approach.
Thanks anyway !

jQuery validate input if element hasClass

I am using the jQuery validation plugin to validate a checkout form on an ecommerce site. The validation works great, however I only need to validate inputs that don't have the class no-validate
Can I use the depends method to do this check? For example, would something like this work:
checkoutForm.validate({
rules: {
firstname: {
required: {
depends: function(element) {
return element.not('.no-validate');
}
}
}
}
});
Or do I have to do something different to do this check? I thought about wrapping the entire rules array in a conditional like:
if(!$(checkoutForm + ' input').hasClass('no-validate') { rules { //rules here } }
but I would rather use the depends method if possible.
Any help/tips would be greatly appreciated!
"The validation works great, however I only need to validate inputs that don't have the class no-validate"
Use the ignore option to ignore those…
checkoutForm.validate({
ignore: '.no-validate',
rules: {
firstname: {
required: true
}
}
});
See: http://jqueryvalidation.org/validate/#ignore

TypeError for jquery validation script

I want to try some simple example with jquery validate plugin in mvc application.
I have a JS module with this method:
ValidateRestriction: function (element) {
var inputs = $('form').validator();
inputs.data("validator").checkValidity();
$(element).validate({
rules :{
field: {
number: true,
"min": "1",
"max": "Infinity"
},
ignore: ".ignore",
onkeyup: false
}
});
}
But in console I get an error:
TypeError: $(...).validator is not a function
var inputs => $('form').validator();
In firebug I see that all needed JS functions are loaded. Verified in console:
>>> $.fn.validate
function()
What's the problem with this?
Your code:
ValidateRestriction: function (element) {
var inputs = $('form').validator();
inputs.data("validator").checkValidity();
$(element).validate({
rules :{
field: {
number: true,
"min": "1",
"max": "Infinity"
},
ignore: ".ignore",
onkeyup: false
}
});
}
These are your issues...
1) No such things as validator() and checkValidity() in the jQuery Validate plugin.
2) You cannot attach .validate() to an input element, assuming that's what your element argument is supposed to be. The .validate() method only gets attached to the form.
3) Your onkeyup and ignore options are placed improperly. These are siblings of the rules option, not siblings of field.
4) I have never heard of setting a max rule to "Infinity". If you leave out a max rule, the max value can be unlimited, or infinite.
5) You do not need quotation marks around the method names, nor do you need quotes around a numerical value.
6) I added the required rule for demonstration. Remove it if you don't want to make the input mandatory.
$(document).ready(function () {
$('#myform').validate({
rules: {
field: {
required: true,
number: true,
min: 1
}
},
ignore: ".ignore",
onkeyup: false
});
});
Working DEMO: http://jsfiddle.net/baCBE/
validator() and checkValidity() are not part of the the jquery validate plugin. Remove the first two lines then try the simplest possible case to see if your setup is correct
$(function(){
$('form').validate();
})
put a class="required" on some elements in your form and test that this is working

Categories

Resources