【问题标题】:Angular material date picker: check invalid date for not required date field角度材料日期选择器:检查不需要的日期字段的无效日期
【发布时间】:2021-11-23 16:49:32
【问题描述】:

Angular 材质日期选择器返回矩对象,它为无效日期格式以及空/空日期字段返回空值。

有什么方法可以区分无效日期格式和空日期。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    如果您使用 Angular 的反应式表单,您可以在表单控件上包含验证器方法,这样它们就会被标记为相应的错误。

    yourForm = this.formBuilder.group({
      date: [null, Validators.required]
    });
    

    您可以通过调用 errors 属性来访问上述抽象控件上的错误,如 documentation 中指定的那样。

    this.yourForm.controls.date.valid;
    // returns true or false
    

    如果要检查特定错误,例如required,可以使用hasError() 方法

    this.yourForm.controls.date.hasError('required');
    

    【讨论】:

      【解决方案2】:

      在 Angular Material 8 中,存在与所需错误不同的格式错误,该错误仅在您拥有 Validators.required 验证器时才会出现。

      如果日期格式错误,您会收到以下错误:

      birthdate.errors = {
        "required": true,
        "matDatepickerParse": {
          "text": "44/3/2020"
        }
      }
      

      所以要区分看“matDatepickerParse”键下的错误。

      如果输入为空,您会得到:

      birthdate.errors = {
        "required": true
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 2017-03-24
        • 1970-01-01
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多