javascript 窗体控件的Angular 设置错误,并在不使用setErrors的情况下使其在窗体组自定义验证程序中无效

toe95027  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(108)

有人能帮我如何设置最小温度错误的温度形式控制在这从组自定义验证器?所以当我键入小于26时,当摄氏度被选中,它应该是无效的,并有最小温度错误,当华氏度被选中,是小于80相同。
自定义验证程序

getTemperatureAndUnitValidator(): ValidatorFn {
    return (form: FormGroup): { [key: string]: any } => {
      const temperatureControl = form.controls['temperature'];
      const selectedTemperatureControl = form.controls['temperatureUnit'];
      const temperature = temperatureControl.value;

      if (selectedTemperatureControl.value.code === 'F' && temperature < 80) {
        return { minTemperature: true };
      } else if (
        selectedTemperatureControl.value.code === 'C' &&
        temperature < 26
      ) {
        return { minTemperature: true };
      }
      return null;
    };
  }

形式群

this.heatIndexForm = new FormGroup(
      {
        temperature: new FormControl(null, [
          Validators.required,
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        humidity: new FormControl(null, [
          Validators.required,
          Validators.min(0),
          Validators.max(100),
          Validators.pattern(/^-?[0-9]\d*(\.\d+)?$/),
        ]),
        temperatureUnit: new FormControl(new Temperature('Celsius', 'C')),
      },
      { validators: this.heatIndexService.getTemperatureAndUnitValidator() }
    );

html中的验证错误

<div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'F' &&
            heatIndexForm.get('temperature').hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 80&deg;F or higher!
          </div>
  <div class="validation-error"
            *ngIf="temperatureUnit.value.code === 'C' &&
            heatIndexForm.controls['temperature'].hasError('minTemperature') &&
            heatIndexForm.controls['temperature'].dirty &&
            heatIndexForm.controls['temperature'].value">
            Temperature must be 26&deg;C or higher!
          </div>

我在自定义验证器中尝试了这个,但它不起作用:(未触发模板中的验证错误,输入未应用红色边框,我使用pInputText,它内置了红色边框,在输入无效时应用)

return {temperatureControl: { minTemperature: true }}

我不想使用.setErrors

vi4fp9gy

vi4fp9gy1#

自定义错误是关于formGroup的,所以应该使用

<div class="validation-error" *ngIf="heatIndexForm.errors?.minTemperature">
   {{heatIndexForm.value.selectedTemperatureControl.code=='F'?
                'Temperature must be 80&deg;F or higher!':
                'Temperature must be 26&deg;C or higher!'}}
</div>

将类添加到输入

<input [class.ng-invalid]="heatIndexForm.errors?.minTemperature &&
                           heatIndexForm.get('temperatureUnit').touched">
..
</input>

注意:你可以在你的验证函数中返回一个复杂的对象,例如.

{minTemperature:true,errorText:'Temperature must be 80&deg;F or higher!'}
//and 
{minTemperature:true,errorText:'Temperature must be 26&deg;C or higher!'}

仅显示{{heatIndexForm.errors?.errorText}}

相关问题