Jquery validation not working second time - javascript

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({ .... });
});

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;
}
}
});
});

jquery number validation not working consistently

I am using jquery validations in a form. I haven't had many issues, however I did run into a problem in a users form where the jquery number validation isn't firing. I tested it in IE, firefox and chrome and it is not working in any of them. The weird part is that so far it seems that it is specific to this one user's form as when I go to other user forms the alerts fire fine as it does in my testing across all browsers. I was wondering if any one else has come across this problem before when using jquery validation. Below is an example of some of the jquery validation code I am using.
var validator = $("#educationForm").validate({
debug: true,
errorElement: "span",
errorClass: "help-block errortext",
errorPlacement: function (error, element) {
element.before(error);
},
success: function (label) {
label.remove();
},
rules: {
school1GPA: {
number: true
},
school2GPA: {
number: true
},
school1Units: {
number: true
},
school2Units: {
number: true
},
},
onsubmit: false
});
$('.form-actions').on('click', '#btnSubmit', function (evt) {
evt.preventDefault();
if ($("#educationForm").valid()) {
$.ajax({
type: "POST",............
} else {
validator.focusInvalid();
}
});
The issue is that you are triggering evt.preventDefault() before you could even trigger jquery validation. That is basically killing any validation statement following evt.preventDefault(). All you need to is just call $("#educationForm").valid() or jquery.validate() and then call evt.preventDefault().
$('.form-actions').on('click', '#btnSubmit', function (evt) {
if ($("#educationForm").valid()) {
evt.preventDefault(); // prevents the form submission to allow ajax
$.ajax({
type: "POST",............
} else {
validator.focusInvalid();
}
});
You should not need your click handler at all. As per documentation, your ajax belongs inside of the submitHandler callback function.
You also should not set onsubmit to false unless you want validation blocked when the submit button is clicked.
debug set to true will block submission of the form.
Something more like this...
var validator = $("#educationForm").validate({
// debug: true, // <- this is blocking the submit entirely
submitHandler: function(form) {
// your ajax here
$.ajax(...);
return false;
},
errorElement: "span",
errorClass: "help-block errortext",
errorPlacement: function (error, element) {
element.before(error);
},
success: function (label) {
label.remove();
},
rules: {
school1GPA: {
number: true
},
school2GPA: {
number: true
},
school1Units: {
number: true
},
school2Units: {
number: true
},
},
// onsubmit: false // <- this is preventing validation on the submit.
});
DEMO: http://jsfiddle.net/2vv8vL79/

Using jQuery Validation Plugin with dynamic form elements

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();
}
};

Simplifying Form validation

I have a form with 5 input fields (4 text input, 1 checkbox) and I have written this code to handle missing information in the input fields. The code works fine but but it seems repetitive and inefficient. Is there a simpler way to write this code?
$("#main-form").on('submit', function(event) {
if (!$("#field1").val()) {
event.preventDefault();
$("#field1-error").html("Error!");
}
else
$("#field1-error").html("");
if (!$("#field2").val()) {
event.preventDefault();
$("#field2-error").html("Error");
}
else
$("#field2-error").html("");
if (!$("#field3").val()) {
event.preventDefault();
$("#field3-error").html("Error");
}
else
$("#field3").html("");
if (!$("#field4").val() && !$("#checkbox1").prop('checked')) {
event.preventDefault();
$("#field4-error").html("Error");
}
else
$("#field4-error").html("");
});
If the function does the same thing on multiple similar fields, it is best to just write one function. I think every Javascript engineer at some point or another has banged their head against a wall trying to come up with a slicker way run form validations.
For this situation I would write the function and call it whenever I needed it. Try this:
$("#main-form").on('submit', function(event) {
myValidations.contentsPresent('#field1', '#field1-error');//call the first field validaitions
myValidations.contentsPresent('#field2', '#field2-error');//second
//third
//etc
});
var myValidations =
{
contentsPresent: function(fieldId, errorId)
{
if (!$(fieldId).val()) {
event.preventDefault();
$(errorId).html("Error!");
}
else
$(errorId).html("");
}
},
contentsPresentCheckBox: function(fieledId, checkboxId, errorId)
{
if (!$(fieledId).val() && !$(checkboxId).prop('checked')) {
event.preventDefault();
$(errorId).html("Error");
}
else
$(errorId).html("");
}
}
}
//Try this.
$(document).ready(function(){
/** Form Validation */
$("#formId").validate({
rules: {
field1:{ required: true },
field2:{ required: true },
field3:{ required: true },
field4:{ required: true }
},
messages: {
field1:{ required: 'Field1 is required!' },
field2:{ required: 'Field2 is required!' },
field3:{ required: 'Field3 is required!' },
field4:{ required: 'Field4 is required!' }
}
// Submit function
});
// This is a simple jquery form validation but you need to include the jquery validation plugin.
http://jqueryvalidation.org/

How to call VieModel function on custom binding Knockout Js

How can I call a ViewModel function inside of a custom binding? I have a custom binding to apply jQuery Validate to a form and I need to call a function in the submitHandler, but nothing I've tried so far works. Can someone point me in the right direction? I've read the documentation, but it's not very clear on the subject.
Here is my custom knockout binding
// activate the jQuery Validate on the form
ko.bindingHandlers.validateEmailForm = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
$(element).validate({
errorLabelContainer: $("#updateEmailFormAlert"),
wrapper: 'li',
rules: {
email: {
required: {
depends: function(element) {
return $("#emailConfirm").is(":filled");
}
},
email: true
},
emailConfirm: {
required: {
depends: function(element) {
return $("#email").is(":filled");
}
},
email: true,
equalTo: "#email",
}
},
messages: {
email: {
required: "Email is required",
email: "Please enter a valid email address"
},
emailConfirm: {
required: "Confirm Email is required",
email: "Please enter a valid confirm email address",
equalTo: "Confirm Email must match Email"
}
},
submitHandler: function() {
bindingContext.$root.updateUserEmail;
return false;
}
});
}
};
Well, you can access the viewModel pretty easily from the custom binding. The current context's viewModel is passed in the viewModel variable, and if you need to access anything else, the bindingContext has access to all parent binding contexts, up until $root.
So if you want to call a function from the viewModel, just do viewModel.someFunction() .
It appears you are already doing something in the submitHandler (bindingContext.$root.updateUserEmail) Is this not what you were looking for?

Categories

Resources