control doesn't show me correct value

70 views Asked by At

I need to use a use a custom validate because I need to check if date is in a correct format

date: [Validators.required,DateValidator.validateDate].

I'm using moment.js to handle the date and this is my validator:

 static validateDate(fdValue: FormControl) {
     const date = fdValue.value;
     console.log(fdValue);

     if(fdValue.errors!=null){
      console.log("error different null");
    }  
     if (date ==null && fdValue.errors!=null && fdValue.errors['matDatepickerParse']!=null){
      return { pattern: {}};
     } 
}

With this validate I put a date in input 13/10/2000 and it works correctly but I put this date "10/0/2000" and it doesn't work.

When I read the console.log(fdValue) result:

errors:
   matDatepickerParse:
     text: "03/0/1977"
   required: true

But when I do fdValue.errors!=null it doesn't enter in these if because fdValue.errors is null. This is impossible because it prints me the value in errors but for the program is null. Anyone can help ?

1

There are 1 answers

0
tomdaly On

If you need to print a message if the date is not correct, you could try:

static validateDate(fdValue: FormControl) {
    if(fdValue.errors) {
        console.log("error message goes here");
    }

    const date = fdValue.value;
    if (date == null) {
        return { pattern: {}};
    }
    return date;
}

I'm not exactly sure what your if statement at the bottom is doing, but edit it as you like - here I've made it so that if your date isn't valid, it will return { pattern: {}}