标签: angular-validation

angular 2:TypeError:this.form.updateValueAndValidity不是函数

在这一点上没有源代码,请随意关注这个问题,我对于角度2开发中的这种痛苦(但必要的)连续弃用模式感到有点厌倦.

所以我升级到rc.4并尝试使用新的forms-api.这就是我得到的:

"TypeError:this.form.updateValueAndValidity不是函数"

上述错误消息对任何人都有意义吗?

谢谢

编辑:好的,源代码毕竟:异常起源于angular中的文件"form_group_directive.js":

FormGroupDirective.prototype.ngOnChanges = function (changes) {
    this._checkFormPresent();
    if (collection_1.StringMapWrapper.contains(changes, 'form')) {
        var sync = shared_1.composeValidators(this._validators);
        this.form.validator = validators_1.Validators.compose([this.form.validator, sync]);
        var async = shared_1.composeAsyncValidators(this._asyncValidators);
        console.log('from within angular:---------------------------------------------------------------------------------------------------');
        console.log(this.form);
        this.form.asyncValidator = validators_1.Validators.composeAsync([this.form.asyncValidator, async]);
        this.form.updateValueAndValidity({ onlySelf: true, emitEvent: false });
    }
Run Code Online (Sandbox Code Playgroud)

console.log-statement的输出是一个"FormGroupDirective",它没有一个名为"updateValueAndValidity"的方法

angular2-forms angular-validation angular

7
推荐指数
1
解决办法
6942
查看次数

FormControl布尔值,在角度2中没有默认值

我在角度2(4.1.2)中使用反应形式

我有一个布尔属性,我不想有一个默认值,但它应该是必需的.

这就是我创建表单的方式:

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
        payedOvertime: [false, Validators.required],
    });
}
Run Code Online (Sandbox Code Playgroud)

而我的HTML:

<div class="form-group">
    <label>Payed overtime</label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="true" />Yes
    </label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="false" />No
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

问题在于,虽然这可以预先选择无线电按钮,但我不想这样,而是必须通过单击其中一个无线电按钮来选择它.如果没有单击任何单选按钮,我希望表单无效.

javascript angular-validation angular angular-reactive-forms

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

反应式表单 - 在取消时跳过验证

我有一个带有取消和提交按钮的反应式表单:

<button (click)="cancel($event)" type="button" class="ui button">Cancel</button>
<button [disabled]="..." type="submit" class="ui button primary">Store</button>
Run Code Online (Sandbox Code Playgroud)

现在,如果我点击提交(商店)按钮,验证就会启动 - 一切都很好。但是如果我点击取消它也会触发验证。我想知道为什么?我不需要对取消进行任何验证。我需要做什么才能关闭它?

angular-validation angular

7
推荐指数
1
解决办法
4479
查看次数

如何区分多个Validators.pattern

我有一个输入,用户需要输入经度.我希望能够在用户输入NaNNot-Precise-Enough值时显示不同的错误消息.我正在使用FormControl.hasError('ValidatorsName')验证来获取错误,但似乎我无法区分这些模式.

模板:

<mat-form-field class="form-field">
    <input matInput placeholder="Logitude" [formControl]="longitude">
    <mat-error *ngIf="longitude.hasError('pattern')">
        Longitude must be <strong>a number</strong>
    </mat-error>
    <!-- I want to be able to check patter2 for example -->
    <mat-error *ngIf="longitude.hasError('pattern')"> 
        Longitude must have <strong>a minimum of 5 decimal numbers</strong>
    </mat-error>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

我的Angular代码:

this.longitude = new FormControl(this.attraction.longitude, [
    // is valid number
    Validators.pattern(new RegExp('(\d{1,3})([.|,]{,1})(\d+))','gi')),
    // is precise enough
    Validators.pattern(new RegExp('(\-{0,1})(\d{1,3})([.|,]{1})(\d{5,13})','i'))
]);
Run Code Online (Sandbox Code Playgroud)

有没有办法给这些模式一个标识符?我会感激任何帮助.

validation angular-validation angular

7
推荐指数
1
解决办法
6268
查看次数

Angular 4验证器同时检查2个控件

我有一个带有2个控件(port_start和port_end)的反应式表单,它们具有以下要求:

  • 两者都必须有价值
  • 它们的值必须介于0到65535之间
  • port_start值必须小于port_end值

这是我到目前为止所尝试的:

[...]
this.formModel.addControl('port_start', 
  new FormControl(object.port_start ? object.port_start : 0, 
  [Validators.required, Validators.min(0), Validators.max(65535), this.minMaxValidator('port_start', 'port_end').bind(this)]));

this.formModel.addControl('port_end', 
  new FormControl(object.ort_end ? object.port_end : 0, 
  [Validators.required, Validators.min(0), Validators.max(65535), this.minMaxValidator('port_start', 'port_end').bind(this)]));
[...]
Run Code Online (Sandbox Code Playgroud)

这是自定义验证器功能:

minMaxValidator = function(startControl : string, endControl : string): ValidatorFn {
  return (control: FormControl): {[key: string]: any} => {
    let valid = true;
    let valStart = 0;
    let valEnd = 0;

    if(this.formModel.controls[startControl] && this.formModel.controls[endControl]) {
      valStart = <number>this.formModel.controls[startControl].value;

      valEnd = <number>this.formModel.controls[endControl].value;
    }

    valid = valEnd >= valStart;

    return valid …
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-reactive-forms

7
推荐指数
2
解决办法
5293
查看次数

验证邮政编码以在 Angular 4 中仅允许长度为 5 或 7 位数字

我正在使用 Angular 4。我想允许zipCode输入字段仅接受长度为 5 或 7 位的输入。

HTML 代码:

<md-input-container class="fill-width-input-wrap">
    <input mdInput placeholder="Zip Code" formControlName="zipCode" minLength="5" maxLength="7" (keypress)="allowOnlyNumbers($event)" required>
    <md-error *ngIf="clientInformationForm.controls['zipCode'].hasError('required')">
        Please enter
        <strong>valid zipcode</strong>
    </md-error>
    <md-error *ngIf="clientInformationForm.controls['zipCode'].hasError('minLength')">
        zip code
        <strong>minimum length is 5</strong>
    </md-error>
</md-input-container>
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular4-forms

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

多个自定义验证器,其反应形式为角度2

我有两个自定义validatorreactive form,我叫下面的函数来创建组件构造函数形式:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.required],
    passwordconfirm: [null, Validators.required]
},
{
    validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});
Run Code Online (Sandbox Code Playgroud)

}

PasswordValidation是一个具有以下两个功能的类

    export class PasswordValidation {

     public  static PasswordMatch(control: AbstractControl) {
        let password = control.get('newpassword'); // to get value in input tag
        if(password){
            let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
            if (password.value !== confirmPassword) {
                control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
            }else {
                return null;
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular-validation angular angular-reactive-forms angular-forms

6
推荐指数
1
解决办法
6199
查看次数

将formControlName用于反应形式的自定义输入组件

有一个自定义的输入组件,它以反应形式用于验证:

@Component({
    moduleId: module.id.toString(),
    selector: 'custom-select',
    templateUrl: 'custom-select.component.html',
    styleUrls: ['custom-select.component.css']
})
export class CustomSelectComponent {
    @Input() public items: SelectModel[];
    public model: SelectModel;
    constructor(private customSelectService: CustomSelectService) {
        this.customSelectService.Selected.subscribe((data: SelectModel) => {
            this.model = data;
        });
    }
    public newSelect(select: SelectModel): void {
        this.customSelectService.updateSelected(select);
    }
}
Run Code Online (Sandbox Code Playgroud)

效果很好,我正在custom-select以反应形式使用,并希望按如下所示进行验证:

<custom-select id="country" [items]="selectItems" formControlName="country"></custom-select>
<div *ngIf=" myFrom.controls['country'].invalid && (myFrom.controls['country'].dirty 
             || myFrom.controls['country'].touched) " class="ha-control-alert">
    <div *ngIf="myFrom.controls['country'].hasError('required')">Country is required</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这就是我在组件中声明表格的方式

this.myFrom = this.formBuilder.group({
    country: [null, Validators.required],
})
Run Code Online (Sandbox Code Playgroud)

但是当我添加formControlName验证时,会出现错误,提示名称为'country'的表单控件没有值访问器。我该如何处理?

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

6
推荐指数
1
解决办法
5381
查看次数

使父 FormGroup 无效,直到嵌套 FormGroup 有效 - FormGroup 的自定义验证器

我有一个用于动态创建表单的 Angular 7 项目。我有一个父 FormGroup,其中包含各种类型的嵌套 FormGroup。

我希望 ParentForm 无效,直到所有嵌套/子表单都有效(实际上希望它们提交但尚未到达)。

  this.parentForm = new FormGroup(this.subforms, { validators: allSubModulesValidValidator }); 
Run Code Online (Sandbox Code Playgroud)

this.subforms 是一个像这样的对象:

interface DynamicKeyFormGroup {
  [key: string]: FormGroup;
}

subforms: DynamicKeyFormGroup = {};
Run Code Online (Sandbox Code Playgroud)

我知道我的验证器是错误的,但我不知道如何为 FormGroup 和 FormControl 设计验证器。

我的想法是,我试图循环遍历所有 this.subForms 的属性(即嵌套的 FormGroups),然后检查它们的状态。如果有无效的,则将parentForm标记为无效。

const allSubModulesValidValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const controls = control.controls;
  for (const key in controls) {
    if (controls.hasOwnProperty(key)) {
      if (!(controls[key].status === 'valid')) {
        return { 'allSubModulesValid': true };
      }
    }
  }
  return null;
};
Run Code Online (Sandbox Code Playgroud)

回应评论。删除验证器后,父级有效,而子级无效: 子无效,父有效

typescript angular-validation angular angular7

6
推荐指数
1
解决办法
1786
查看次数

使用动态/更新参数的 Angular 7 自定义验证

我正在使用 Angular 7 和材料设计组件

我需要将 requireMatch 验证添加到 mat-autocomplete 中。

我已经使用参数创建了自定义验证,但参数值确实会动态变化。

下面是我的组件代码。

this.stepFormGroup = this.formBuilder.group({
    AccessCode: ["", [Validators.required, this.requireMatch(this.accessCodeList)]]
});

////require-match validation for access-code
requireMatch = (accessCodes: string[]) => {
    return (control: FormControl) => {
        const selection: any = control.value;
        console.log("accessCodes", accessCodes, "selection", selection);
        if (accessCodes.indexOf(selection)===-1) {
            return { requireMatch: true };
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

accessCodes我面临的问题是我的内部总是空的(init)requireMatch

的更改this.accessCodeList不会反映到验证器。

意味着更改后this.accessCodeList它不会在requireMatch验证器中获得更新的数组。

那么有人知道如何在自定义验证器中传递动态参数吗?

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

6
推荐指数
1
解决办法
7405
查看次数