종료 날짜가 jQuery를 사용하여 시작 날짜보다 큰지 확인하십시오.
종료 날짜 [텍스트 상자]가 시작 날짜 [텍스트 상자]보다 큰지 jQuery에서 어떻게 확인 / 확인합니까?
융합을 확장하는 것뿐입니다. 이 확장 방법은 jQuery 유효성 검사 플러그인을 사용하여 작동합니다. 날짜와 숫자를 확인합니다.
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(params).val());
}
return isNaN(value) && isNaN($(params).val())
|| (Number(value) > Number($(params).val()));
},'Must be greater than {0}.');
그것을 사용하려면 :
$("#EndDate").rules('add', { greaterThan: "#StartDate" });
또는
$("form").validate({
rules: {
EndDate: { greaterThan: "#StartDate" }
}
});
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
그렇게해야한다고 생각합니다
파티에 조금 늦었지만 여기는 내 부분
Date.parse(fromDate) > Date.parse(toDate)
세부 사항은 다음과 같습니다.
var from = $("#from").val();
var to = $("#to").val();
if(Date.parse(from) > Date.parse(to)){
alert("Invalid Date Range");
}
else{
alert("Valid date Range");
}
jquery.validate.js 및 jquery-1.2.6.js를 참조하십시오. 시작일 텍스트 상자에 startDate 클래스를 추가합니다. 종료 날짜 텍스트 상자에 endDate 클래스를 추가합니다.
이 스크립트 블록을 페이지에 추가하십시오.
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('.startDate').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
$('#formId').validate();
});
</script>
도움이 되었기를 바랍니다 :-)
나는 danteuno의 대답을 땜질하고 있었고 , 의도는 좋지만 슬프게도 IE 가 아닌 여러 브라우저에서 깨졌습니다 . IE는 Date생성자에 대한 인수로 받아들이는 것에 대해 상당히 엄격 하지만 다른 것들은 그렇지 않기 때문입니다. 예를 들어 Chrome 18은
> new Date("66")
Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)
이로 인해 코드가 "날짜 비교"경로를 취하고 모든 것이 거기에서 내리막 길로 이동합니다 (예 : new Date("11")보다 크며 new Date("66")원하는 효과의 반대 임).
Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().
In the end, the code becomes:
$.validator.addMethod(
"greaterThan",
function(value, element, params) {
var target = $(params).val();
var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
if (isValueNumeric && isTargetNumeric) {
return Number(value) > Number(target);
}
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date(target);
}
return false;
},
'Must be greater than {0}.');
The date values from the text fields can be fetched by jquery's .val() Method like
var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();
I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.
If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.
If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:
http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/
So I needed this rule to be optional and none of the above suggestions are optional. If I call the method it is showing as required even if I set it to needing a value.
This is my call:
$("#my_form").validate({
rules: {
"end_date": {
required: function(element) {return ($("#end_date").val()!="");},
greaterStart: "#start_date"
}
}
});//validate()
My addMethod is not as robust as Mike E.'s top rated answer, but I'm using the JqueryUI datepicker to force a date selection. If someone can tell me how to make sure the dates are numbers and have the method be optional that would be great, but for now this method works for me:
jQuery.validator.addMethod("greaterStart", function (value, element, params) {
return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');
I like what Franz said, because is what I'm using :P
var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}
$(document).ready(function(){
$("#txtFromDate").datepicker({
minDate: 0,
maxDate: "+60D",
numberOfMonths: 2,
onSelect: function(selected) {
$("#txtToDate").datepicker("option","minDate", selected)
}
});
$("#txtToDate").datepicker({
minDate: 0,
maxDate:"+60D",
numberOfMonths: 2,
onSelect: function(selected) {
$("#txtFromDate").datepicker("option","maxDate", selected)
}
});
});
Or Visit to this link
jQuery('#from_date').on('change', function(){
var date = $(this).val();
jQuery('#to_date').datetimepicker({minDate: date});
});
In javascript/jquery most of the developer uses From & To date comparison which is string, without converting into date format. The simplest way to compare from date is greater then to date is.
Date.parse(fromDate) > Date.parse(toDate)
Always parse from and to date before comparison to get accurate results
function endDate(){
$.validator.addMethod("endDate", function(value, element) {
var params = '.startDate';
if($(element).parent().parent().find(params).val()!=''){
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date($(element).parent().parent().find(params).val());
}
return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";
}else{
return true;
}
},jQuery.format('must be greater than start date'));
}
function startDate(){
$.validator.addMethod("startDate", function(value, element) {
var params = '.endDate';
if($(element).parent().parent().parent().find(params).val()!=''){
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
}
return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
}
else{
return true;
}
}, jQuery.format('must be less than end date'));
}
Hope this will help :)
First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018
after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.
var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");
d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);
if (parseInt(d1) > parseInt(d2)) {
$('#fromdatepicker').val('');
} else {
}
this should work
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('#date_open').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
If the format is guaranteed to be correct YYYY/MM/DD and exactly the same between the two fields then you can use:
if (startdate > enddate) {
alert('error'
}
As a string comparison
'Programing' 카테고리의 다른 글
| 파일에 텍스트를 어떻게 추가합니까? (0) | 2020.08.20 |
|---|---|
| Rails에서 현재 시간에 10 일을 추가하는 방법 (0) | 2020.08.20 |
| 프로그래밍 방식으로 ngClick을 트리거하는 방법 (0) | 2020.08.20 |
| Kotlin에서 지연 후 함수를 호출하는 방법은 무엇입니까? (0) | 2020.08.20 |
| WPF에 DesignMode 속성이 있습니까? (0) | 2020.08.19 |