I am using jquery bassistance validation and need to verify that a start date is after an end date. I am wondering if anyone knows if this functionality exists and if I can add rules to do this or if I have to add a custom check. I am having difficulty finding any examples of this that work with my code which forwards to another function if the form is valid. (pasted below)
$("#hotels").validate({
rules: {
checkinDate: {
date: true
},
checkoutDate: {
date: true
}
}
});
$("#hotels input.submit").click(function() {
var isValid = $("#hotels").valid();
if (isValid == true) {
} else {
hComp();
return false;
}
} else {
return false;
}
});
I saw this in another example, but am not sure how I could use it.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
Thanks in advance for any assistance.
That example looks like it's exactly what you need. Have a look here.
Borrowing from that jquery example, suppose you have the following HTML:
<input id="startDate" value="Jan 12, 2009" />
<input id="endDate" value="Jan 12, 2010" />
Then this JavaScript code should show the alert "Start date is before end date!" (assuming the values aren't modified):
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
alert("Start date is before end date!");
}
I ended up solving this problem before validation, which is probably a much better idea anyway. Here's the solution using the jquery ui datepicker. Then I can just use the same logic to do a final validation check.
$('input').filter('.datepicker').datepicker({
beforeShow: customRange,
showOn: 'both',
buttonImage: contextPath + '/assets/images/icon-calendar.gif',
buttonImageOnly: true,
buttonText: 'Show Date Picker'
});
function customRange(a) {
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
if (a.id == 'checkoutDate') {
if ($('#checkinDate').datepicker('getDate') != null) {
c = $('#checkinDate').datepicker('getDate');
}
}
return {
minDate: c
}
}
Related
Added the following td. The date value is coming as a format 01 Aug 1990. I want to sort that column. But it is not working. How can I properly set the data-sort-value so that it sort in correct way
<td data-sort-value="${info.offDate}" class="${someclass}">${info.offDate}</td>
I have the following javascript for sorting -
$(function() {
$("#infoListTable").tablesorter({
textExtraction: function(node) {
var attr = $(node).attr('data-sort-value');
if (typeof attr !== 'undefined' && attr !== false) {
return attr;
}
return $(node).text();
},headers: {
dateFormat: 'dd-mm-yyyy',
6: { sorter:'otherDate' }
}
});
});
The built-in parser for 'dd-mm-yyyy' doesn't understand month names. It is expecting all numerical values.
You can add your own parser. Since modern browsers are able to parse new Date("dd MMM yyyy"), the parser is very simple (demo):
$.tablesorter.addParser({
id: 'date-dd-MM-yyyy',
is: function() {
return false;
},
format: function(str) {
var date = str ? new Date(str) : str;
return date instanceof Date && isFinite(date) ? date.getTime() : str;
},
type: 'numeric'
});
$('table').tablesorter({
headers: {
6: { sorter: 'date-dd-MM-yyyy' }
}
});
Additionally, the textExtraction method can be simplified to:
textExtraction: function(node) {
return $(node).attr('data-sort-value') || $(node).text();
}
since the jQuery .attr() function will return an empty string if undefined instead of false.
I am doing the live search using the jquery plugins. When I tried to search that doesn't exist, it only shows the table. I would like to put some message "No result found" if it doesnt exist. The question is how can I add message "No result found"
Note: In my codes I add some validation, the user need input minimum of 3 characters
/**
**options to have following keys:
**searchText: this should hold the value of search text
**searchPlaceHolder: this should hold the value of search input box placeholder
**/
(function($)
{
$.fn.tableSearch = function(options)
{
if(!$(this).is('table'))
{
return;
}
var tableObj = $(this),
searchText = (options.searchText)?options.searchText:'Search: ',
searchPlaceHolder = (options.searchPlaceHolder)?options.searchPlaceHolder:'',
divObj = $('<div style="font-size:20px;">'+searchText+'</div><br /><br />'),
inputObj = $('<input style="min-width:25%;max-width:50%;margin-left:1%" type="text" placeholder="'+searchPlaceHolder+'" />'),
caseSensitive = (options.caseSensitive===true)?true:false,
searchFieldVal = '',
pattern = '';
inputObj.off('keyup').on('keyup', function(){
searchFieldVal = $(this).val();
if(searchFieldVal.length == 0)
{
tableObj.find('tbody tr').show();
}
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
});
tableObj.before(divObj.append(inputObj));
return tableObj;
}
}(jQuery));
Here into JQ plugin(Posted at your question), the handler for empty result is exist. See piece of code from it.
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
Paraphrase you mistaken at your end. Re check it.
I am using a kendo datetimepicker. When user opens the calender and select any date I need to check for some other dates, ie need to run validations if the date is wrong then prevent the new date from filling the date picker and keep the old value, otherwise allow datepicker to change value. I tried with event.preventDeafult , but unfortunatly it is not working..
Is there any way to acheceive this?
Here is the fiddle enter link description here
Any help is appreciated.
Example fiddle here
$("#datePicker").kendoDatePicker({
change:function(event){ alert(1);
// some validations here
event.preventDeafult(); }
});
Go through this answer. May any lines help you to solve your problem. You can simply assign like this.
$("#datepicker").kendoDatePicker({
change: function () {
// some validations here
var i = 0;
var prev = "9/12/2014";
var date = kendo.toString(this.value(), 'd');
if (i == 0) {
$("#datepicker").data("kendoDatePicker").value(prev);
}
},
close: onClose,
open: onOpen
});
Updated Answer :
var date;
$(function () {
date = $("#datepicker").data("kendoDatePicker").value();
$("#datepicker").kendoDatePicker({
change: function () {
// some validations here
var i = 0;
var prev = date;
if (i == 0) {
$("#datepicker").data("kendoDatePicker").value(prev);
}
},
close: onClose,
open: onOpen,
});
})
I've used read only in the past to do this.
var endDate = $("#endDate").data("kendoDatePicker");
endDate.readonly();
I have two dropdowns on an form. If the user selects a value from the first dropdown, I want to make sure they make a choice from the second dropdown. I'm new to knockout, so I'm not sure how to do this. I don't think I need a fullblown validation library. I just want to stop the action so the popup doesn't go away and some text appears saying "hey you, pick something!"
The row looks like this:
<div class="channelRow" data-bind="foreach: channels">
<div class="channelPrompt">CHANNEL: </div>
<select class="channelSelect" name="channels" data-bind="options: $root.financialVM.channelOptions(), value: name, optionsCaption: '--'"></select>
<div class="portPrompt">NUMBER OF PORTS: </div>
<select class="portSelect" name="ports" data-bind="options: $root.financialVM.portOptions(), value: port, optionsCaption: '--'"></select>
</div>
Update:
Here's the function that I'm working with. Edge is a modal window that appears and is where the select boxes are.
function Edge (siteA, siteB, key, channelpair) {
var edge = this;
edge.siteA = ko.observable(siteA);
edge.siteB = ko.observable(siteB);
edge.distance = ko.observable(0);
edge.key = ko.observable(key);
edge.channels = ko.observableArray([
new ChannelPair()
]);
edge.addChannel = function () {
if(edge.channels().length >= 3) return;
edge.channels.push(new ChannelPair());
};
}
function ChannelPair () {
var channel = this;
channel.name = ko.observable();
channel.port = ko.observable(0);
channel.port.extend({
required: {
message: "You can not have a name without a port",
onlyIf: function () { return (self.name() != null); }
}
});
}
Ok here is a complete solution for you:
// You need this config in order to kick things off
ko.validation.configure({
messagesOnModified: true,
insertMessages: true
});
function Edge (siteA, siteB, key, channelpair) {
var edge = this;
edge.siteA = ko.observable(siteA);
edge.siteB = ko.observable(siteB);
edge.distance = ko.observable(0);
edge.key = ko.observable(key);
edge.channels = ko.observableArray([
new ChannelPair()
]);
edge.addChannel = function () {
if(edge.channels().length >= 3) return;
edge.channels.push(new ChannelPair());
};
}
function ChannelPair () {
var channel = this;
channel.name = ko.observable();
// Extending happens on declaration not after wards
channel.port = ko.observable(0).extend({
required: {
message: "You can not have a name without a port",
// self doesn't mean anything here so replace it with channel like this
onlyIf: function () { return (channel.name() != null); }
}
});
// you need a property called errors to keep your validation group in it
channel.errors = ko.validation.group(channel);
}
Also remember to add knockout validation to your project. Its a plugin and not shipped as part of knockout out of the box.
I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.
<script type="text/javascript" language ="javascript" >
$(function () {
var date = new Date();
var currentDate = date.getDate();
var currentMonth = date.getMonth();
var currentYear = date.getFullYear();
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
$(".datepicker").datepicker({ maxDate: new Date(currentYear, currentMonth, currentDate) });
});
</script>
How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.
Any answers Please?
Thank you.
I had a similar requirement for my code with a hire date. Here's how I did it:
$('#hireDate').datepicker({
dateFormat: 'dd/mm/yy',
maxDate: new Date(currentYear, currentMonth, currentDay)
});
The user can still enter a future date manually and weasel around your date picker. We had this problem on a production system.
If you want to additionally validate the date using the validation plugin, try this:
/**
* Requires Datepicker and Validator
*
* Params:
* 0...dateformat. see datepicker
* 1...date. Value "0" is "today"
* 2...(optional). date to display. will be automatically filled if 0 and 1 are set.
* usage:
* myfield: { maxDate: ['m/d/yy', 0] }
*/
jQuery.validator.addMethod("maxDate",
function(value, element, params) {
if (!params[0])
throw 'params missing dateFormat';
if (typeof(params[1]) == 'undefined' )
throw 'params missing maxDate';
var dateFormat = params[0];
var maxDate = params[1];
if (maxDate == 0) {
maxDate = new Date();
maxDate.setHours(0); // make it 00:00:0
maxDate.setMinutes(0);
maxDate.setSeconds(0);
maxDate.setMilliseconds(0);
}
if (typeof(params[2]) == 'undefined' )
params[2] = $.datepicker.formatDate(dateFormat, maxDate);
try {
var valueAsDate = $.datepicker.parseDate( dateFormat, value )
return (valueAsDate < maxDate);
} catch (x) {
return false;
}
},'Must be greater than {2}.');
$("#myform").validate({
rules: {
datepicker : {
maxDate ['m/d/yy', 0]
}
}
});
HTML:
<input name="datepicker" class="datepicker" type="text"/>