This question already has answers here:
Validate that end date is greater than start date with jQuery
(16 answers)
Validate end_date is after start_date [duplicate]
(1 answer)
Closed 5 years ago.
I've an input field where users can insert a date between a date range.
So I added a new method on JQuery validator object:
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
}
Then I added a new class rules:
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
And finally I added the class to the input:
$("#myField").addClass("myDateFieldRangeValidate");
So, how can I pass the two dates to the validation function?
UPDATE: Added a code snippet
$.validator.addMethod("dateRange", function(value, element, from, to){
try {
var date = new Date(value);
if(date >= from && date <= to)
return true;
} catch(e) {
}
return false;
});
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {fromDate, toDate}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#btnValidate").click(function(){
$("#frm1").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<form id="frm1">
Date <input type="text" id="myField">
<input type="button" id="btnValidate" value="Validate">
</form>
Thanks to Arun P Johny, I post here his fiddle:
$.validator.addMethod("dateRange", function(value, element, params) {
try {
var date = new Date(value);
if (date >= params.from && date <= params.to) {
return true;
}
} catch (e) {}
return false;
}, 'message');
var fromDate = new Date("2017-02-01");
var toDate = new Date("2017-12-31");
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#frm1").validate();
$("#btnValidate").click(function() {
console.log($("#frm1").valid())
});
jQuery(function($) {
var validator = $('#myform').validate({
rules: {},
messages: {}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<form id="frm1">
Date
<input type="text" id="myField" value="16 Feb 2017">
<input type="button" id="btnValidate" value="Validate">
</form>
Here is a way to have jQuery validator with the feature to give the start date and the end date
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>
<script>
$( document ).ready(function() {
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
var startDate= new Date(jQuery(element)[0].attributes['data-rule-startDate'].value);
var endDate= new Date(jQuery(element)[0].attributes['data-rule-endDate'].value);
var d = new Date(value);
console.log(d)
return (d.getTime() <= endDate.getTime() && d.getTime() >= startDate.getTime())
}, "Please enter a valid date."
);
$('#frm1').validate();
});
</script>
<html>
<form id="frm1">
Date <input type="text" id="myField" name="myField" data-rule-optdate="true" data-rule-startDate="2017-12-12" data-rule-endDate="2018-12-12">
</form>
</html>
Related
I don't understand why when I use the condition value like a > b but it doesn't work properly, maybe because of the value a = decimal. following my code:
HTML
<input type="text" class="form-control" name="numberdays" id="numberdays" value="10.0/>
<input type="text" name="cutii" id="cutii" value="9.0">
<button class="btn btn-primary waves-effect" id="subcut" type="submit" disabled>
SCRIPT
cutifrom.addEventListener('input',()=>{
if (cutii.value > numberdays.value) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
the result is that my button is disabled, it shouldn't be.
here's my js. actually number days I use the datepicker and generate numbers that are automatically generated. maybe because it's the condition that I use the operator is not detected.
JS for datepicker
<script type="text/javascript">
$(document).ready(function(){
let $fromDate = $('#fromdate'),
$toDate = $('#todate');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
});;
});
$(function() {
let $fromDate = $('#fromdate'),
$toDate = $('#todate'),
$numberDays = $('#numberdays'),
$numberCuti = $('#cuti');
$fromDate.datepicker().on('change', function(){
$toDate.datepicker('option', 'minDate', $(this).val());
$numberDays.val(calculateDateDiff($toDate.val(), $(this).val()));
});
$toDate.datepicker().on('change', function(){
$fromDate.datepicker('option', 'maxDate', $(this).val());
$numberDays.val(calculateDateDiff($(this).val(), $fromDate.val()));
});
cutifrom.addEventListener('input',()=>{
if (parseFloat(cuti.value) >= parseFloat(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
function calculateDateDiff(endDate, startDate) {
if (endDate && startDate) {
let e = moment(endDate),
s = moment(startDate);
return e.diff(s, "days");
}
return null;
}
});
</script>
Your value is a String type and the comparison is not like Number, try converting the value to a number and see if it works.
You need to change the code to this form:
cutifrom.addEventListener('input',()=>{
if (Number(cutii.value) > Number(numberdays.value)) {
subcut.removeAttribute('disabled');
}else{
subcut.setAttribute('disabled','disabled');
}
}) ;
Good Luck :)
I have code to disable specific dates on jquery datepicker. code runs fine on my local environment but not working on GoDaddy windows hosting
var disableddates = result; //result is array of dates ["1/7/2018","1/8/2018","1/9/2018"]
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay : DisableSpecificDates
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay : DisableSpecificDates
});
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('mm/dd/yy', date);
console.log(string); //this string return with leading zero 01/07/2018...
return [disableddates.indexOf(string) == -1];
}
This code run fine on local but when making it live it is not disabling specific dates in jQuery datepicker.
You do not need to format the date if it's already in a date format. For example, if result contains an array date like "1/7/2018", you can create a Date object from this:
var newDate = new Date(result[0]);
With this in mind, you can easily make and manipulate a Date. DatePicker passes a Date object to the function too. Here is a solution you might try:
$(function() {
var disableddates = ["1/7/2018", "1/8/2018", "1/9/2018"];
$("#txtFromdate, #txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: "m/d/yy"
});
$("#txtFromdate").change(function() {
$("#txtTodate").datepicker("option", "minDate", $(this).val());
});
function DisableSpecificDates(date) {
var result = [true];
$.each(disableddates, function(k, v) {
var exclude = new Date(v).toString();
var today = date.toString();
if (exclude == today) {
console.log("Match", exclude, today);
result = [false];
}
});
return result;
}
});
label {
width: 60px;
}
input {
width: 10em;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="txtFromdate">From:</label>
<input type="text" id="txtFromdate" />
<label for="txtTodate">To:</label>
<input type="text" id="txtTodate" />
My Testing done here: https://jsfiddle.net/95t81vzq/3/
Hope that helps.
The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here. Just trying to test a simply validation.
<div class="cell">
<label>DOB</label><br>
<input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">
</div>
<script type="text/javascript">
function checkForm(form)
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(form.dob.value != '' && !form.dob.value.match(re)) {
alert("Invalid date format: " + form.dob.value);
form.dob.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}
<div class="cell">
<label>DOB</label><br>
<input id="startdate" type="text" placeholder="01/01/1980" onblur="checkForm()">
<script>
function checkForm()
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
var date = document.getElementById("startdate").value;
alert(date);
if(date != '' && !date.match(re)) {
alert("Invalid date format: " + date);
date.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}
</script>
</div>
enter code hereSuggest me on this..
While creating Date ref(java script), text box value should be treated as dd/MM/yyyy format..
function myFunction1(a)
{
//Here the input format should be dd/MM/yyyy...
//But Date ref taking it as MM/dd/yyyy
var x=new Date(a);
alert(x);
if(x>new Date())
{
alert("Wrong date");
}
else
{
alert("Success");
}
}
----
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onClick="myFunction1(document.getElementById('textbox1').value)" type="button" value="Execute" />
Try this:
var dateString = document.getElementById('<textboxid>').value;
var day = parseInt(dateString.substring(0,2));
var month = parseInt(dateString.substring(3,5));
var year = parseInt(dateString.substring(6,10));
alert(new Date(year, month - 1, day));
To Validate Date, Use this code:
alert(/^(0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](0[1-9]|1[012]|[1-9])[- /.](\d{4})$/.test(dateString));
It will return true if the date is valid else return false.
Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.