2

In the DB I have a column name time and it's type time,

On my code I'm using nestjs with class-validator and the user send this value for time 10:13:06 ( Assuming it is in 12h format ).

How do I validate this value using class-validator

current code

import {
  IsDateString,
  IsNotEmpty,
} from 'class-validator';

export class CreateFilmTime {

  @IsDateString() // O know it's for date string
  time: Date;

}

2 Answers 2

3

You could use @Matches with a regex like this:

  @Matches(/^(1[0-2]|0?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$/)
Sign up to request clarification or add additional context in comments.

Comments

0

You can reference @IsMilitaryTime decorator the class-validator documentation

  const now = new Date();

  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');

 `${hours}:${minutes}` //hh:mm

According to the documentation, checks if the string represents a time without a given timezone in the format HH:MM (military). If the given value does not match the pattern HH:MM, then it returns false.

Concatenate to use and pass the validation using:

@IsMilitaryTime()
readonly time: string;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.