【问题标题】:CSS Invalid selector not working with reactive formCSS无效选择器不适用于反应形式
【发布时间】:2019-06-07 20:57:35
【问题描述】:

我遇到了一个问题,我无法将 :invalid css 选择器与我的输入绑定,因为我有自定义验证。 invalid 仅在基本验证器示例中有效:输入 type="email" 因此无效将与 example@ 或 example@example.exmaple 一起使用,而我的函数仅验证最后一个(example@example.example)。 Project Link

HTML 文件

<input class="custom-input" type="email" [(ngModel)]='Email' name="email" placeholder="Email" formControlName="emailTxt">
<div class="err>
   this is an error
</div>

打字稿文件

this.signUpForm = this._fb.group({
   emailTxt: [null, Validators.compose([
     Validators.required
   ])]
 }, {
     validators: [
       EmailValidation('emailTxt'),
     ]
   });

表单验证函数

export function EmailValidation(controlName: string) {
  return (formGroup: FormGroup) => {
    const control = formGroup.controls[controlName];

    if (control.errors && !control.errors.invalidEmail) {
      return;
    }
    if (control.value.trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
      control.setErrors({ invalidEmail: true });
    }
    else {
      control.setErrors(null);
    }
  }
}

CSS 文件

.custom-input:invalid{
    & ~ .err {
      max-height: 200px;
      padding: 0 18px 10px 20px;
      color: red;
    }
}

我希望每个 control.setErrors() 函数都应该触发无效的选择器

【问题讨论】:

  • 它的工作示例在哪里?
  • 您好刚刚更新了描述中的问题链接。

标签: html css angular angular-reactive-forms


【解决方案1】:

在您的项目中添加下面的 CSS 代码,这绝对有效

input.ng-dirty.ng-invalid {
  border: 1px solid red;
}

【讨论】:

  • 非常感谢
【解决方案2】:

这肯定会工作☺添加到你的css文件

input.ng-invalid.ng-touched, select.ng-invalid.ng-touched {
    border: 1px solid red !important;
}

【讨论】:

  • +1 如果我想在焦点输出时显示错误消息,这实际上有效,它实际上有助于感谢您的回答。
猜你喜欢
  • 2019-06-16
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2014-05-18
  • 2015-12-29
相关资源
最近更新 更多