Using jQuery Validation Plugin with dynamic form elements - javascript

I have a page that contains multiple forms, and each form can contain any number of elements that have a common root in its name. I'm trying to use this answer to validate a form when it's submitted, but I get a TypeError: a.data(...) is undefined error on jquery.validate.js. My code is below.
var valForm = function(kit_id) {
$('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
$("#frm_" + kit_id).validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
if (! $("#frm_" + kit_id).valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};
The function is called when a link is clicked.
Save
Any suggestions?

I think you have to call .validate() on the form before you can call .rules() on the inputs in that form. You should also call .rules() only on the inputs in the form you're submitting.
var valForm = function(kit_id) {
var form = $("#frm_" + kit_id);
form.validate({
errorElement: "div",
errorPlacement: function(error, element) {
$("#error_modal").html(error);
}
});
form.find('input[name^="kit_desc_"]').each(function() {
$(this).rules("add", {
required: true,
messages: {
required: "Please enter a description"
}
});
});
if (! form.valid()) {
// a dialog box will appear listing the errors.
$("#error_modal").dialog();
}
};

Related

Jquery validation, alert just once

If I run below, and both fields alder and gender is invalid, it'll alert two times. Is it possible to make it alert just once?
$(function(){
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
alert("Alert once");
}
});
});
errorPlacement is called once for every error - it's not meant to alert a message, but to place it in the form. You can either try to use the groups feature, to group you fields together and get a single call for the entire group, or use the showErrors function to capture all errors and present them however you like:
$(".selector").validate({
showErrors: function(errorMap, errorList) {
alert(`Your form contains ${this.numberOfInvalids()} errors`);
}
});
Never used jQuery validate before but this might work:
$(function(){
var checked = false;
$("#formTest").validate({
rules : {
alder : {
required: true
},
gender : {
required: true
}
},
errorPlacement: function (error, element) {
if (!checked) {
alert("Alert once");
checked = true;
}
}
});
});

How to dynamically add a validation rule using jquery validation plugin

I'm trying to dynamically add a validation rule to some dynamic controls using http://jqueryvalidation.org/ but its not working.
$(".rtxt").each(function () {
$(this).rules('add', {
required: true
});
});
<input class='rtxt' name='txtDocName' id='txtDocName' style='width:220px;' type='text' >
Don't know what i am missing here.
I can't use 'required' attribute as its not supported by IE9 so i will have to use jquery validation plugin.
Here is fiddle
http://jsfiddle.net/ed4fg1xo/
Also, i need to do validation on div click event.
$(document).ready(function () {
// 1. prepare the validation rules and messages.
var rules = {
textbox1: {
required: true,
minlength: 2
},
textbox2: "required",
textbox3: "required"
};
var messages = {
textbox1: {
required: "textbox1 is required",
minlength: "textbox1 needs to be at least length 2"
},
textbox2: "textbox2 is requried",
textbox3: "textbox3 is required"
};
// 2. Initiate the validator
var validator
= new jQueryValidatorWrapper("FormToValidate",
rules, messages);
// 3. Set the click event to do the validation
$("#DivIdName").click(function () {
if (!validator.validate())
return;
alert("Validation Success!");
});
});

Multiple instances of jQuery Validation Plugin on a JSP page

SOLVED: $.extend() twice in a row simply overwrites the previous object because objects are passed by reference. My fix was to do this:
var updateUserObj = $.extend({}, validationPluginDefaults);
var newUserObj = $.extend({}, validationPluginDefaults);
Then the validators are executed like this:
var whateverValidator = $.extend(updateUserObj,{new rules})
Update: Further research shows that what I'm trying to do appears to be correct but the problem may be in the object I am extending - "validationPluginDefaults"). Here it is below:
var validationPluginDefaults = {
ignore: [],
errorElement: 'p', //default input error message container <p>
errorClass: 'text-error', // default input error message class
focusInvalid: true, //focus on the first invalid field
messages: {},
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (el) { // hightlight error inputs
//jQuery(el).closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (err, el) {
jQuery(el).next(".text-error").hide();
jQuery(el).next(".text-error").remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onfocusin: function () {},
onfocusout: function () {}
};
From my testing it appears that even though I have two separate forms on a JSP page and each has different validation that I can still only use one jQuery Validate Plugin instance per page; is this correct?
Here's my code:
// Define validation rules for form one
var formOneValidator = $.extend(validationPluginDefaults,{
rules: {
firstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
lastName: {
minlength: 2,
required: true,
},
email: {
required: true,
email: true
}
}
});
var formTwoValidator = $.extend(validationPluginDefaults,{
rules: {
newFirstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
newLastName: {
minlength: 2,
required: true,
},
newEmail: {
required: true,
email: true,
}
}
});
$("#formOne").validate(formOneValidator);
$("#formTwo").validate(formTwoValidator);
What happens here is that formOne validator takes on all the rules of formTwoValidator after this code executes.
Is the solution to have only one validator and swap out rules depending on which form I'm in? It just seems strange that I wouldn't be able to define separate validators for each form on the page. Am I fundamentally misunderstanding something here?
you could use knockout and give each page a different view model which handles the different validation. That is how i would do it but i'm sure there will be a better answer.

Jquery validation not working second time

The problem is this jquery validation is not working in my form second time. Its working first time perfectly but second time its shows error message but form is going to submit. The code is here
(function ($, W, D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function () {
//form validation rules
$("#aspnetForm").validate({
rules: {
firstname: "required",
lastname: "required",
company: "required",
jobtitle: {
required: true,
},
phone: {
required: true,
number: true
},
email: {
required: true,
email: true
},
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
company: "Please enter your company name",
jobtitle: "Please enter your job title",
phone: "Please enter a valid phone number",
email: "Please enter a valid email address",
},
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
//form.submit(function (e) {
// e.preventDefault();
// if (flag) {
// createListItem();
// }
//});
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
$('#newsletterModal').on('hidden.bs.modal', '.modal', function () {
clearFields();
});
$('#newsletterModal').on('shown.bs.modal', function (e) {
$('#lblMsg').empty();
});
});
})(jQuery, window, document);
can any one help me
Your submitHandler callback function...
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
}
Do not put a submit event handler inside of the submitHandler callback! It's unclear to me what you're trying to do but the submitHandler callback function of the plugin has already captured & replaced the default submit event of the form.
Also, whenever you declare your own submitHandler function, you are over-riding the default built into the plugin. Since I see nothing inside of your custom submitHandler that submits the form, the form will never be submitted.
You'll either need to remove the submitHandler to allow the form to be submitted (when valid) as per the default functionality OR you'll need to put $(form).submit() inside of it someplace.
submitHandler: function (form) {
if (flag) {
createListItem();
}
$(form).submit();
}
NOTE:
Wrapping up everything like this is superfluous, unnecessary, verbose, and arcane...
(function($,W,D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function() {
$("#aspnetForm").validate({ .... });
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
The entire mess above can be removed and simply replaced by putting the .validate() method inside of the DOM ready event handler function...
$(document).ready(function() {
$("#aspnetForm").validate({ .... });
});

Jquery custom validation with Html 5 data attributes and default value

I am trying to build a custom client side jquery validation and trying to ignore default values that i generate from HTML5 data attributes
$('input, textarea').each(function () {
if ($(this).data('val-default')) {
$(this).focus(function () {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function () {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
So with the above code i can add default values to input and textarea elements like this
data-val-default="Type your first name here"
Placeholder attribute is unfortunately not an option yet
The problem now is that i am trying to validate these elements with Jquery validation like this
$.validator.addMethod("ignoreDefaultValues",
function (value, element) {
if ($(element).data('val-default'))
return !($(element).data('val-default') == element.value);
return true;
},
"Required field"
);
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
Here is an example of an input element
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
The jquery validation seems to ignore the rules. if i test for example by typing an empty space it will validate and alert "NOT VALID" but it just ignores my custom validation.
What am i doing wrong?
Have i missed anything?
You need to setup the validation before the submit function. So instead of doing $(this).valid(...) in your submit handler, instead do this beforehand:
$('form#contact-form').validate( { //your rules
,
submitHandler:function(){
alert('Is Valid!');
$(this).submit(); //or submit via AJAX, or whatever you planned...
},
invalidHandler:function(){
alert('Is not valid!');
}
});

Categories

Resources