jQuery validate plugin with datepicker - invalid date causes datepicker popup on submit - asp.net-mvc-3

I have a simple MVC3 form that has a date field and client side validation enabled (jquery.validate / jquery.validate.unobtrusive). I've added code to attach a datepicker (jQuery UI) to the date field per the documentation. However, if the datepicker is the last thing I click prior to clicking the submit button and the date field is invalid, it causes the datepicker for that field to automatically show itself. I don't want this. How can I disable?
Edit:
After reviewing the code for the validation plugin, it looks like it tries to manually focus on the last active input control using the focusInvalid() function below:
focusInvalid: function() {
if( this.settings.focusInvalid ) {
try {
$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
.filter(":visible")
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger("focusin");
} catch(e) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
There appear to be 2 options for dealing with this. One is to set the focusInvalid setting on the validator itself to false. I opted to monkey patch the focusInvalid function instead because it allows me to focus on the FIRST invalid element in the form, not necessarily the last active element.
$('form').data('validator').focusInvalid = function () {
$(this.currentForm).find('.input-validation-error').first().focus();
};
I'd be interested to hear any other approaches to this problem, however.

If acceptable in your case, you could show the datepicker only using a button, using the following datepicker options:
showOn: 'button', showButtonPanel: true, buttonImage: '<your image file>',
buttonImageOnly: true,
buttonText: 'Choose a Date',
If you do it this way the datepicker won't automatically display in case validation fails when submitting the form.

Related

Knockout date validation ob

My question is in reference to an older question on Stack Overflow:
Knockout validation
The question is regarding date validation in knockout.js and knockout.validation.js.
Does anyone have a good example of knockout binding in MVC 4 that validates a date entry?
Using the above link I implemented the following sample:
ko.validation.rules['simpleDate'] = {
validator: function (val, validate) {
return ko.validation.utils.isEmptyVal(val) || moment(val, 'MM/DD/YYYY').isValid();
},
message: 'Invalid date'
};
next, I bound the rules:
self.ChildDateOfBirth = ko.observable().extend({ simpleDate: true });
The whole idea behind this is if the user enters 14/02/2009 then loses focus then a message should popup next to the box as invalid date.
I must be doing something wrong...
Did you call ko.validation.registerExtenders(); after you added the validation rule?
According to the documentation you need to call it.
It's working in my jsfiddle.

How to reset the dropdown value to the old value in jqgrid

I have a simple dropdown with two values.Lets say Staus:active and inactive.
During the onchange event, I want to perfrom some validation and revert back if the validation fails. Thai is if I change from active-inactive and my validation fails, I should change the dropdown back to active.
So far I am able to catch the on change event through the dataevents options of editOptions.
Below is my code, Thanks for the assist.
editoptions:{value:{Y:'Active',N:'Inactive'}, dataEvents:[
{
type: 'change',
fn: function(e) {
alert("inside change trigger");
$grid.setColProp('Status', { editoptions:{value:{Y:'Active',N:'Inactive'}}});
}
}
]}
I also read I have to set recreate form :true. I tried that also.
I would recommend you to consider to make the column non-editable or to readonly/disabled if the validation condition could be checked before editing will be started. It shows the user more clear that the field mayn't be changed.
Alternatively you can get savedRow parameter of jqGrid if you use inline editing mode or cell editing mode (with var savedRows = $(this).jqGrid("getGridParam", "savedRow")). To get the "old" data in case of form editing you can just get the data of selected row by using getGridParam with selrow (or alternatively from the hidden field of the form which have id="id_g". Something like var serRowId = $("#id_g").val();) and by using getRowData/getCell.

what is right jQuery event for a input field with timepicker

I have a input field that is formatted with the data-format HH:mm:ss PP. When the timepicker is clicked the focus on the input field don't appear that's why I couldn't use onblur event. What i want is like keydown or keyup event but it seems doesn't work in my case because focus is out in the input field so what jQuery event should i used?
change seems to work fine:
Fiddle
$("#datepicker").datepicker()
.on("change", function () {
console.log("Changed");
});
Example is with datepicker(), I'm not sure what your timepicker implementation is as it's not in the jquery(ui) api. But it should work as well.
Edit: after looking at the datetimepicker you are using, based on the DOM I'm seeing as a result of datetimepicker() - I think this should work for you:
Fiddle
$('#datetimepicker1').closest(".well").next(".bootstrap-datetimepicker-widget").on("click", "*", function () {
console.log("Changed");
});
Just make sure this is after your datetimepicker() call. Note that this will be triggered on any click within your calendar/time picker even if it is a click on something that is already selected (no change).
If you want, you could store the last value of your input and then check that if it changed before continuing with this event callback function. If it did change, be sure to update the variable you are holding the "last value" in... something like this.
If possible, the best option would actually be to modify datetimepicker()'s js to call a function or trigger an event from the same place it updates the text input. Looking at the code:
set: function () {
var formatted = "";
if (!this._unset) formatted = this.formatDate(this._date);
if (!this.isInput) {
if (this.component) {
var input = this.$element.find("input");
input.val(formatted);
input.trigger("change"); // added this
this._resetMaskPos(input)
}
this.$element.data("date", formatted)
} else {
this.$element.val(formatted);
this.$element.trigger("change"); //added this
this._resetMaskPos(this.$element)
}
},
With the two lines I added above, you should be able to rely on a change event bound to the input element.

Validate (Bassistance) before sending to fancybox

I'm using the bassistance validation plugin and have a small script that catches the second submit-button (called preview) and sends the data via ajax to fancybox. I'ld like to validate the forms before they are send to fancybox. At the moment they're only validatet, if I send the forms via the submit-button. I tried in various ways (e.g. I put the call for validation directly after the if and so on) but couldn't get it work. Maybe there's a way to let validate know that it should also react, when the preview-button is hit?
My Code:
$(function() {
$('#myform *').tooltip();
$('#myform ').validate();
});
$(document).ready(function(){
$(':submit').click(function(){
for (var i in CKEDITOR.instances){
CKEDITOR.instances[i].updateElement();
}
var value = $(this).attr("id");
if (value == 'preview') {
$.fancybox.showLoading();
$.ajax({
type : "POST",
cache : false,
url : "../mypath/",
data : $('#myform').serializeArray(),
success : function(data) {
$.fancybox(data, {
'minWidth': '100%',
'minHeight': '100%',
});
}
});
return false;
}
});
});
If i'm not wrong, the Bassistance Validator plugin relies on the fact that if you SUBMIT a form, and the requirements are not met, the function returns a "false" on that submit, enabling you to visually see the errors made.
In your source code, you correctly initialized the Bassistance validator plugin at the very beginning of your code ( I assume you created the rules for it directly on the input fields for example minlength="2" required ) but there is a problem: there is no hook for the SUBMIT event of the submit button, but only for the CLICK event on that button.
There is a simple example on the Bassistance website that shows how you can use custom submit events for the plugin:
http://jquery.bassistance.de/validate/demo/ajaxSubmit-intergration-demo.html
Basically, what you need to do is to insert the intelligent part of your code into
jQuery("#yourform").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
/*
Here you can do the following:
1) Update the instances of CKEDITOR
2) Check if the submit is in the preview mode
3) If yes
- do your fancy stuff
- return false so that the real submit is not triggered
If not
- return true so that the real submit handler is evaluated by the browser and the POST is triggered
*/
});
}
});

How to solve problem when use jquery datepicker and validation in the same time

When I used datepicker with trigger icon so that users could choose date from clicking this icon or type directly in textbox (txtDate), I also used jquery validation to require textbox must be not empty.
But when a user submit the form with empty textbox (txtDate.Text=""), the error message of validation push trigger icon to the right. Could you tell me the solution? Thank you very much!
$('#some_form').validate({
rules: {...},
messages: {...},
errorPlacement: function(error, element) { //solve you problem
var trigger = element.next('.ui-datepicker-trigger');
error.insertAfter(trigger.length > 0 ? trigger : element);
}
});
The errorPlacement function receives two parameters - the error message and the validated element. Use the latter to decide whether or not to customize the placement for your fields (for example, by adding a class):
$('form').validate({
rules: {...},
errorPlacement: function(error, element) {
if (element.hasClass('customError')) {
// custom error placement
}
else {
element.after(error); // default error placement
}
}
});

Resources