标签: angular-validation

角度自定义异步验证器不起作用

这是演示plnkr。我正在尝试为具有文本框和验证按钮的OTP输入实现自定义异步验证器。我只想在用户单击验证OTP按钮或表单提交按钮时验证输入。目前,验证是针对文本更改事件进行的,因此无法正常工作。 表单HTML:

<form [formGroup]="registrationForm" (ngSubmit)="registrationForm.valid && submitRegistration(registrationForm.value)" novalidate>
  <fieldset class="form-group">
    <label for="e-mail">Mobile</label>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="Mobile" formControlName="mobile">
      <span class="input-group-btn">
        <button class="btn btn-secondary" type="button">Send OTP</button>
      </span>
    </div>
    <div class="form-text error" *ngIf="registrationForm.controls.mobile.touched">
      <div *ngIf="registrationForm.controls.mobile.hasError('required')">Mobile is required.</div>
    </div>
  </fieldset>
  <fieldset class="form-group">
    <label for="e-mail">Verify OTP</label>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="OTP" formControlName="otp">
      <span class="input-group-btn">
        <button class="btn btn-secondary" (click)="veryOTPAsyn(otp)" type="button">Verify</button>
      </span>
    </div>
    <div class="form-text error" *ngIf="registrationForm.controls.otp.touched">
      <div *ngIf="registrationForm.controls.otp.hasError('required')">OTP is required.</div>
      <div *ngIf="registrationForm.controls.otp.hasError('invalidOtp')">OTP is invalid.</div>
    </div>
  </fieldset>
  <button class='btn btn-primary' type='submit' [disabled]='!registrationForm.valid'>Submit …
Run Code Online (Sandbox Code Playgroud)

javascript validation angular-validation angular angular-forms

5
推荐指数
2
解决办法
2485
查看次数

FormGroup 获取字段值:TypeError:无法读取未定义的属性“get”

我正在尝试对“passwordConfirm”字段进行验证,但出现一个奇怪的错误:ERROR TypeError: Cannot read property 'get' of undefined 这是我的代码:

loginForm: FormGroup;


ngOnInit(){
    this.loginForm = new FormGroup({
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'password': new FormControl(null, Validators.required),
      'passwordConfirm': new FormControl(null, [Validators.required, this.checkIfMatchingPasswords.bind(this)]),
    });
}



checkIfMatchingPasswords() {
    return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : { notSame: true} // error
  }
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-forms

5
推荐指数
1
解决办法
1万
查看次数

如何在不沉默孩子自己的验证器的情况下向角度中的子表单控件添加错误

this.form = this.fb.array([
  this.fb.group({ 
    username: [null, Validators.required]
  }),
  this.fb.group({ 
    username: [null, Validators.required]
  }),
  ...
], uniqueUsernameValidator)

const uniqueUsernameValidator = control => {
  // find duplicate
  
  // when flagging the error
  control.get('0.username').setErrors(ifThereIsAnError) // where `ifThereIsAnError` could be null
}
Run Code Online (Sandbox Code Playgroud)

以某种方式uniqueUsernameValidator静默required子表单字段指定的验证。如何解决这个问题呢?

validation angular-validation angular angular-reactive-forms angular-forms

5
推荐指数
1
解决办法
3503
查看次数

ngRepeat 内的角度表单验证

我有一系列表行,其中有 ng-repeat 内的各种输入,我尝试使用 Angular 内置的表单验证来处理所需的字段。一切正常,除了当我删除数组中支持 ng-repeat 的项目之一时。

这是我设置验证的方式

<td ng-class="{ 'has-error' : vm.testForm.itemName{{$index}}.$invalid }">
  <input type="text" 
         name="itemName{{$index}}" 
         class="form-control" 
         ng-model="item.name" 
         required />
  <div class="help-block" 
       ng-show="vm.testForm.itemName{{$index}}.$invalid" 
       ng-messages="vm.testForm['itemName'+$index].$error">
    <span ng-message="required">Name is required</span>
  </div>
</td>
Run Code Online (Sandbox Code Playgroud)

Plunker 显示我的问题

https://plnkr.co/edit/Q1qyqlSG69EXR2lTrsHk

在 plunker 中,如果删除第一个表行,您会注意到虽然最后一行仍然无效,但错误已附加到上面的行。然后,当您填写最后一行以使其有效,然后再次清空它时,错误仍然显示在错误的行上。删除后续行只会使错误远离实际的无效行,直到它们根本不出现在表上。

我应该有其他方法来验证这些输入吗?

angularjs angularjs-ng-repeat angular-validation

4
推荐指数
1
解决办法
2960
查看次数

如何引用ngFor中添加的控件?

我在模板驱动的表单中使用ngFor添加了几个输入,我想在输入无效时添加相应的错误消息.通常,如果我没有使用ngFor,我会使用#inputName ="ngModel".为了引用动态添加的输入,我有什么方法可以做这样的事情吗?

基本上我想做这样的事情:

<div *ngFor="let field of fields; let i = index">
        <label>{{field.label}}</label> <input [ngModel]="field.value" required #field{{i}}="ngModel" />
        <div *ngIf="field{{i}}.invalid"> This field is required </div>
</div>
Run Code Online (Sandbox Code Playgroud)

angular2-template ngfor angular-validation angular

4
推荐指数
1
解决办法
3548
查看次数

在FormArray中的控件的模板内部访问验证器的状态

我正在使用Angular的反应形式,并希望根据控件的invalid属性的值将CSS样式应用于FormArray中的控件。我想出了以下方法,但我认为ngClass属性中的表达式太长且太复杂。是否有更简洁的方法来访问FormArray中控件的无效属性?

模板:

<form [formGroup]="myForm" class="form-horizontal">
    <div class="form-group" [ngClass]="{'has-error': myForm.controls.name.invalid }">
        <label class="control-label">Name</label>
        <input formControlName="name" type="text" class="form-control" />
    </div>
    <div formArrayName="array1">
        <div *ngFor="let f of array1_FA.controls; let i = index" [formGroupName]="i">
            <div>
                <div class="form-group" 
                    [ngClass]="{'has-error': myForm.controls.array1.at(i).controls.question.invalid}">

                    <label class="control-label">Question #{{i+1}}</label>
                    <input formControlName="question" class="form-control" type="text" />
                </div>
                <div class="form-group" 
                    [ngClass]="{'has-error': myForm.controls.array1.at(i).controls.response.invalid}">

                    <label class="control-label">Answer #{{i+1}}</label>
                    <input formControlName="response" class="form-control" type="text" />
                </div>
            </div>
        </div>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

零件:

import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'form-array-validation', …
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-reactive-forms

4
推荐指数
1
解决办法
1438
查看次数

Angular 2自定义验证器,用于检查何时需要两个字段之一

我正在尝试实现自定义验证器功能来检查是否输入了电话号码(家庭电话和移动电话).我想在两个字段上显示错误消息,当它们被触摸并且没有有效值时,由于某种原因我的代码没有按预期工作.请帮帮我这篇文章.-谢谢!这是stackblitz链接https://stackblitz.com/edit/angular-ve5ctu

createFormGroup() {
   this.myForm = this.fb.group({
     mobile : new FormControl('', [this.atLeastOnePhoneRequired]),
     homePhone : new FormControl('', [this.atLeastOnePhoneRequired])
   });
}

atLeastOnePhoneRequired(control : AbstractControl) : {[s:string ]: boolean} {
  const group = control.parent;
  if (group) {
    if(group.controls['mobile'].value || group.controls['homePhone'].value) {
      return;
    }
  }
  let errorObj = {'error': false};
  return errorObj;
}
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-reactive-forms

4
推荐指数
1
解决办法
2679
查看次数

自定义控件中的setValidators,无需Angular中的引用

我创建了一个自定义输入控件。我不想创建任何自定义验证。我想使用默认必需的minLength,maxLength等。我知道我可以这样做

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
Run Code Online (Sandbox Code Playgroud)

但是我无法从父组件发送表单引用。我如何在文本框组件内使用setValidator。

// input-box.component.ts    
    import { Component, Input, forwardRef } from '@angular/core';
    import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';


    @Component({
      selector: 'app-input-box',
      template:`<label >{{inputdata.label}}</label><br>
      <input type="text" required #textBox [value]="textValue" (keyup)="onChange($event.target.value)" />`,
      styleUrls: ['./input-box.component.less'],
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => InputBoxComponent),
          multi: true
        },
        /*{
          provide: NG_VALIDATORS,
          useExisting: forwardRef(() => InputBoxComponent),
          multi: true,
        }*/]
    })
    export class InputBoxComponent implements ControlValueAccessor {
      @Input() inputdata: any;
      private textValue: any = '';

      onChange(value) {
        this.textValue = value;
        this.propagrateChange(value);
      }

      private …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular-validation angular angular4-forms angular5

4
推荐指数
1
解决办法
2309
查看次数

多个表单字段上的 Angular 异步验证器

我正在尝试在 FormControl 上实现异步验证器,它依赖于同一表单的另一个字段的值。为了以同步方式完成相同的任务,我只需创建一个验证器函数,并将其附加到 FormGroup 验证器。

/**/
mySyncValidator(form: FormGroup): { [s: string]: boolean } {
    const field1 = form.get('field1').value;
    const field2 = form.get('field2').value;
    ...
};
Run Code Online (Sandbox Code Playgroud)

现在,我应该怎么做才能以异步方式完成完全相同的事情(基本上是调用执行 httpClient 请求的服务)?

Angular 文档中提供的所有示例都与单个 FormControl 验证相关(据我所知,如果将验证器附加到单个 FormControl,则无法访问其他 FormControl)https://angular.io/guide/form-validation#creating-asynchronous-验证者

谢谢

asynchronous angular-validation angular

4
推荐指数
1
解决办法
1480
查看次数

Angular 2 - 错误:没有 FormControl 的提供者

我为社区编写一个库,它需要访问表单控件并监听更改的值。

这是我之前使用 Angular 2.3 和 4.0 时的做法。

export class ValidationMessageDirective implements OnInit {

    @Input('validationMessage') customMessage: string;
    constructor(private el: ElementRef, private formControl: NgControl, private validationMessageService: ValidationMessageService) {
        this.target = $(el.nativeElement);
        this.formGroup = this.target.closest('.form-group');

        this.formControl.valueChanges.subscribe((newValue) => {
            this.checkValidation();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但升级到 Angular 4.1 后,此代码不再起作用。这是我得到的错误: ERROR Error: Uncaught (in promise): Error: No provider for NgControl!

有什么建议或想法让我聆听指令中更改的值吗?

更新1: 这是我的index.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ValidationMessageDirective …
Run Code Online (Sandbox Code Playgroud)

angular-directive angular-providers angular-validation angular

3
推荐指数
1
解决办法
1万
查看次数