there is a string "05/05/2022" how to check that it can be a date, but "5.1" should not be a date Date example
05.05.2020
05/05/2020
05/05/2020;22:40
an example of not a date but a numbers
5
5.1
5.23
CodePudding user response:
This can be done with a regex like ...
/^\d{1,2}(?<separator>[./])\d{1,2}\k<separator>\d{2}(?:\d{2})?(?:\s*;\s*\d{2}:\d{2})?$/
... or .../^\d{2}(?<separator>[./])\d{2}\k<separator>\d{4}(?:\s*;\s*\d{2}:\d{2})?$/
... where the former is more forgiving with the date format in terms of digit count of day(1
or 2
), month(1
or 2
) and year(2
or 4
) whereas the latter enforces a strict digit count of 2,2,4
for e.g. dd/mm/yyyy
.
Both patterns utilize a named capturing group for the date separator (either .
or /
) which will be used as named backreference in order to ensure a correct date format.
Both patterns also feature the optional match for a time format ... [(?:\s*;\s*\d{2}:\d{2})?
] ... which might possibly follow a valid date format.
const multilineSample =
`5.5.20
5.5.202
5.5/2020
05.05.2020
05/05.2020
05/05/2020
05/05/2020;22:40
5
5.1
5.23`;
// see ... [https://regex101.com/r/6CwyXy/1]
const regXDateFormatLooseDigitCount =
/^\d{1,2}(?<separator>[./])\d{1,2}\k<separator>\d{2}(?:\d{2})?(?:\s*;\s*\d{2}:\d{2})?$/gm;
// see ... [https://regex101.com/r/6CwyXy/2]
const regXDateFormatStrictDigitCount =
/^\d{2}(?<separator>[./])\d{2}\k<separator>\d{4}(?:\s*;\s*\d{2}:\d{2})?$/gm
console.log(
'sample data ...\n',
multilineSample
);
console.log(
'result for loose digit count ...',
multilineSample.match(regXDateFormatLooseDigitCount)
);
console.log(
'result for strict digit count ...',
multilineSample.match(regXDateFormatStrictDigitCount)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
CodePudding user response:
Assuming that you'll be only getting numbers or date and nothing other than these two inputs :
// Assuming that you'll be getting either a date or a number
let checkDate = (val)=>{
let count = 0 ;
for(let i=0 ; i<val.length ; i )if(val[i]==='.')count ;
if(count<=1)return false;
return true;
}
let date1 = "05.05.2022";
if(checkDate(date1))console.log(date1 " is a date");
else console.log(date1 " is a number");
let date2 = "5.34";
if(checkDate(date2))console.log(date2 " is a date");
else console.log(date2 " is a number");