简体   繁体   中英

control doesn't show me correct value

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?

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: {}}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM