Skip to content

Commit

Permalink
feat: add isValidGermanDate and isValidTime (german date and time val…
Browse files Browse the repository at this point in the history
…idation)
  • Loading branch information
Ralf77 committed Feb 5, 2024
1 parent 90e1471 commit b6b7ad5
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/date.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
formatGermanFullDateTime,
isFuture,
isToday,
isValidGermanDate,
parseGermanDate,
parseGermanDateFlexible,
parseIsoDate,
Expand Down Expand Up @@ -63,6 +64,35 @@ describe('formatGermanDateTime', () => {
});
});

describe('isValidGermanDate', () => {
it('should determine if a string matches the german date format dd.mm.yyyy', () => {
expect(isValidGermanDate('01.01.2000')).toEqual(true);
expect(isValidGermanDate('1.1.2000')).toEqual(true);
expect(isValidGermanDate('1.01.2000')).toEqual(true);
expect(isValidGermanDate('01.1.2000')).toEqual(true);
expect(isValidGermanDate('011.1.2000')).toEqual(false);
expect(isValidGermanDate('01.111.2000')).toEqual(false);
expect(isValidGermanDate('01.01.200')).toEqual(false);
expect(isValidGermanDate('xx.01.2000')).toEqual(false);
expect(isValidGermanDate('01.yy.2000')).toEqual(false);
expect(isValidGermanDate('01.01.zzzz')).toEqual(false);
expect(isValidGermanDate('')).toEqual(false);
expect(isValidGermanDate('..')).toEqual(false);
expect(isValidGermanDate('abc')).toEqual(false);
});
});

describe('isValidTime', () => {
it('should determine if a string matches the time format HH:mm', () => {
expect(isValidGermanDate('12:55')).toEqual(true);
expect(isValidGermanDate('1:55')).toEqual(false);
expect(isValidGermanDate('12:5')).toEqual(false);
expect(isValidGermanDate('')).toEqual(false);
expect(isValidGermanDate(':')).toEqual(false);
expect(isValidGermanDate('abc')).toEqual(false);
});
});

describe('isToday', () => {
it('should determine if a date is today', () => {
expect(isToday(new Date())).toEqual(true);
Expand Down
21 changes: 21 additions & 0 deletions src/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,27 @@ export function isFuture(date: Date | string | number): boolean {
return isAfter(date, new Date());
}

export function isValidGermanDate(date: string): boolean {
const regexGermanDateFormat = /^(\d{1,2}[.]\d{1,2}[.]\d{4})$/;

if (date.match(regexGermanDateFormat)) {
return true;
}

return false;
}

export function isValidTime(time: string): boolean {
const regexTimeFormat = /^(\d{2}[:]\d{2})$/;

if (time.match(regexTimeFormat)) {
return true;
}

return false;
}


export function parseDate(value: string, formatString: string): Date | null {
const parsedDate = parse(value, formatString, new Date());

Expand Down

0 comments on commit b6b7ad5

Please sign in to comment.