Reputation: 65
<html>
<head>
<script lang="Javascript">
function validateExpDate(){
var expdate ="24-10-2018";
var fields = expdate.split('-');
var date = parseInt(fields[0]);
var month = parseInt(fields[1]);
var year = parseInt(fields[2]);
var today = new Date();
var dd = parseInt(today.getDate());
var mm = parseInt(today.getMonth()+1); //January is 0!
var yyyy = parseInt(today.getFullYear());
if(year >= yyyy){
if(month >= mm){
if(date > dd){
alert('Valid Expiry Date');
}
}
}else{
alert('Invalid Expiry Date Entered!');
}
}
</script>
</head>
<body onload="validateExpDate();">
</body>
</html>
I want to compare the date in variable expdate with current date and display appropriate message. Can anyone figure out the problem and make it work?
Upvotes: 2
Views: 59
Reputation: 65
Thanks guys. I figured out the problem was just curly brasis. Thanks for the effort of replying. Really Appreciated.
Upvotes: 0
Reputation: 4574
You are not handling the else
conditions for date and month. Either you can write code like below or you can use &&
in first IF
loop if that suits you.
if (year >= yyyy) {
if (month >= mm) {
if (date > dd) {
alert('Valid Expiry Date');
} else {
alert('Invalid Expiry Date Entered!');
}
}
else {
alert('Invalid Expiry Date Entered!');
}
} else {
alert('Invalid Expiry Date Entered!');
}
Upvotes: 0
Reputation: 3257
Your else
instruction belongs to the outer if
statement. In your case the if
statement returns true
(2018 >= 2018) so the program jumps to the code inside of the first if-clause. From then on your else
statement is no longer reachable for the program.
You are looking for something like this:
<html>
<head>
<script lang="Javascript">
function validateExpDate(){
var expdate ="24-10-2018";
var fields = expdate.split('-');
var date = parseInt(fields[0]);
var month = parseInt(fields[1]);
var year = parseInt(fields[2]);
var today = new Date();
var dd = parseInt(today.getDate());
var mm = parseInt(today.getMonth()+1); //January is 0!
var yyyy = parseInt(today.getFullYear());
if(year >= yyyy && month >= mm && date > dd)
{
alert('Valid Expiry Date');
}
else{
alert('Invalid Expiry Date Entered!');
}
}
</script>
</head>
<body onload="validateExpDate()">
</body>
</html>
You have all conditions in one if clause. By using the AND operator this statement returns only true if all conditions are true. If one of them is false the program will go inside the else clause.
It is also possible to compare two dates directly in javascript. Just a little less code...
<html>
<head>
<script lang="Javascript">
function validateExpDate(){
var expdate = new Date('2018-10-24');
var today = new Date();
if(expdate > today) {
alert('Valid Expiry Date');
}
else {
alert('Invalid Expiry Date Entered!');
}
}
</script>
</head>
<body onload="validateExpDate()">
</body>
</html>
Upvotes: 1