首页 > 解决方案 > CSS无效选择器不适用于反应形式

问题描述

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

文件

<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() 函数都应该触发无效的选择器

标签: htmlcssangularangular-reactive-forms

解决方案


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

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

推荐阅读