I am doing validation using angular js. For date validation, I am using the moment.js
file. My issue is when I am entering the date which is having a year as '0000' eg 1-1-0000, it is not giving the error. My directive code is below-
app.directive("validDate", function () {
return {
require: "ngModel",
restrict: "A", // Attributes only
link: function (scope, elem, attr, ctrl) {
ctrl.$validators.cValidDate = function(value) {
if (value === undefined || value === null || value === "") {
return true;
}
return moment(value, ["D-M-YYYY"], true).isValid();
}
}
}
});
Can anybody help me in my validation? I have created a plunker here- PLUNKER
I have edited the script, But still it is now giving error for all dates less than 1-1-1970, because it is taking date 1-1-0001 as 1-1-1970 so it is validation according to it, also when no value is there in date, date is shown as invalid untill and unless I enter the date greater than 1-1-1970. I wanted that if year is 0000 date should not be valid. Can anybody help me? I have updated my plunker with the above code.
Update-
Now I am able to resolve the date issue but my problem is now that- if date is empty still the error is there I don't want this error when date is empty, what condition should I put for this? Please see my updated plunker.
Answer-
I am able to made my answer, as I added the below condition -
if(moment(value, ["D-M-YYYY"], true).isValid()){
// condition
} else
return true;
see my new plunker here- https://plnkr.co/edit/uKcynQktBCKRYoN7xdM1?p=preview
Native JS Date object thinks there is a year zero as well. Year zero is acceptable per ISO 8601 , which uses astronomical year numbering. In this system, year 0 = 1 BCE, year -1 = 2 BCE, and so forth.
This is not true for many databases. So better set a date must be greater than validation in the subject you need.
if(moment(value, ["D-M-YYYY"], true).isValid())
{
//alert(moment(value, ["D-M-YYYY"], true).isSameOrAfter(moment("1-1-0001"), ["D-M-YYYY"], true));
if(moment(value, ["D-M-YYYY"]).isSameOrAfter(moment("1-1-0000"), ["D-M-YYYY"]) )
return true ;
else
return false;
}else
{
return false;
}
you might want to add a function that checks for the value of the year alone. My solution is not elegant but it does the trick.
function checkYear (v) {
v = v.split("-");
if(v[2] === "0000"){
return true;
}
/* or you could go for a year of your choice*/
/*
if(parseInt(v[2]) <= 1900){
return true;
}
*/
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.