Drop down and datepicker triggers on jquery validation - javascript

I am using codeigniter where I have autocomplete drop down and datepicker. If values are not selected then I am applying validations using jquery. Validations run properly but when I click on submit button drop down list or date picker gets auto trigger if not selected. I dont understand why this is happening
Date Picker is
$(function ()
{
$('#search_date').datepicker
({
format: "dd-mm-yyyy",
autoclose: true,
clearBtn : "true" ,
startDate: new Date() ,
})
});
validations are
$( document ).ready(function() {
$(":submit").on('click',function(){
$('#search_form').validate({
rules: {
loading:
{
required:true
},
discharge:
{
required:true
},
search_date:
{
required:true
}
},
messages: {
loading:
{
required:"Required!"
},
discharge:
{
required:"Required!"
},
search_date:
{
required:"Required!"
}
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.parent());
},
submitHandler: function (form) {
if ($(form).valid())
form.submit();
return false; // prevent normal form posting
}
});
});
});

Related

How do I trigger a jQuery code while using the jQuery validation library?

I am using jQuery validation library to validate both password inputs to have the same value. My code is written below.
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
return true;
}
});
I want to execute a jQuery code to add a class to an element when the notification of password_2 appears.
I want to modify this part of the code by adding a jQuery script inside the messages: {} but the code below does not work. You can see that I added $(".woocommerce-form-row--last").addClass("notif-triggered");
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
$(".woocommerce-form-row--last").addClass("notif-triggered");
},
Any help is greatly appreciated. Thanks.
You don't tell us, but I'll assume you're using the validation library linked here.
You should be able to add functionality within an invalidHandler, e.g. something think this:
$(".woocommerce-ResetPassword").validate({
onfocusout: false,
onkeyup: false,
rules: {
password_2: {
equalTo: "#password_1"
}
},
messages: {
password_2: "<div class='woocommerce-password-strength bad'>Passwords do not match</div>"
},
submitHandler: function(form) {
$(".woocommerce-form-row--last").removeClass("notif-triggered");
return true;
},
invalidHandler: function(event, validator) {
$(".woocommerce-form-row--last").addClass("notif-triggered");
}
});

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/

Submit handler is working but its very slow

Hello guys I am submitting my form using submit handler and its working but its very slow. Please help me to make it fast. Thanks in advance
Following is my javascript code for login form......
var handleLoginForm = function () {
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
It was fast when i was submitting the form using php but I must have to use javascript to submit this form......
Run the JS when the form is submitted:
$(".login-form").submit(function(){
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
});
This keeps the JS from running until the form is submitted.
UPDATE:
$(".login_form").submit(function(){
$(this).validate({ ... });
});
Not sure if this will work, but the repeated selector seemed a bit awkward to me.
I solved the same problem by changing the implementation of submitHandler like below. I just take the first item [0] of the forms selector.
submitHandler: function (form) {
$(".login-form input")[0].submit();
...
}

Automatically close qtip2 using JQuery .validate()

I'm working on a form which implements QTip2 to display a tooltip once someone tries to submit a form where data is missing. Everything works as intended, however I would like the tooltip to be removed once the error class is removed (effectively once someone types in the input field). I have the following code for my validation currently:
$('#form0').validate({
rules: {
Name: "required",
Email: {
required: true,
email: true
},
Subject: "required",
Message: "required"
},
errorPlacement: function (error, element) {
$('#Name').qtip({
content: 'Please enter your name',
position: {
target: 'mouse', // Track the mouse as the positioning target
adjust: { x: 5, y: 5 } // Offset it slightly from under the mouse
},
style: { classes: 'qtip-red' }
});
return true;
},
errorClass: "form-error"
});
As you can see, once someone tries to submit the form the class "form-error" is assigned to the input field, so I would like the tooltip to be removed as well once this class is removed. I tried the following, but it did not work, not sure why:
onHide: function() { $(this).qtip('destroy'); }
I found a solution to this problem by adding the following code inside errorPlacement {}:
events: { show: function (event, api) { if (!element.hasClass('form-error')) event.preventDefault(); } },
show: {
delay: 0,
target: element
},
hide: { target: element },

How to validate kendo DateTimePickerFor using mvc 4 razor?

i wants to validate kendo DateTimePickerFor on client side.My control on view as
#(Html.Kendo().DateTimePickerFor(m => m.StartDate)
.HtmlAttributes(new { style = "width:200px", #class = datePicker",required = "true" })
.Name("StartDate")
.Depth(CalendarView.Year)
.Value(DateTime.Now.ToString())
.Min(DateTime.Now.ToString())
.Max(DateTime.Now.AddMonths(4))
.Format("MM/dd/yyyy hh:mm tt")
)
i have masked it in ready function.but it allows me to type any input.
$(document).ready(function () {
$('.datePicker').mask('99/99/9999');
$('#_appointmentCreateForm input[type="text"], textarea').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right',
appendTo: "#_appointmentCreateForm"
});
$('#_appointmentCreateForm').validate({
ignore: [],
rules: {
StartDate: {
required: true
}
},
messages: {
StartDate: {
required: "Please choose Date and Time."
}
},
errorPlacement: ValidatorErrorPlacement,
success: ValidatorSuccess
}
);
});
And when there is no value in datetimepicker i.e datetimepicker is empty then validation gets fail but not showing any message.
So, any ideas how I can validate the Kendo DateTimePicker to accept valid input format? Thanks in advance.
You can define
Html.Kendo().DateTimePickerFor(model => model.date_debut)
.ParseFormats(new string[] { "dd/MM/yyyy HH:mm" })
on the control. But this will be a server side validate as Html.Kendo() will generate the control from the model.
To validate it in client side, the best way is to test when the submit is fired.
$.submit(function(e) {
//test if form is ok
});
My problem has been solved!when i changed my ready function to
$(document).ready(function () {
$('.datePicker').mask('99/99/9999');
$('#_appointmentCreateForm input[type="text"], textarea').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right',
appendTo: "#_appointmentCreateForm"
});
$('#_appointmentCreateForm').validate({
ignore: [],
rules: {
Speciality: {
selectspeciality: true
}
},
messages: {
Speciality: {
selectspeciality: "Please select Speciality."
}
},
errorPlacement: ValidatorErrorPlacement,
success: ValidatorSuccess
}
);
$.validator.addMethod("selectspeciality", function (value, element) {
var isValid = $(element).data("kendoDropDownList").selectedIndex == 0 ? false : true;
return this.optional(element) || isValid;
}, "Please select Speciality.");
});
Ho[e it will help someone like me.

Categories

Resources