简体   繁体   English

Angular 验证器允许 null 或应用长度

[英]Angular Validator to allow null or apply length

I have searched online but could not find a solution for this yet.我已经在网上搜索过,但还没有找到解决方案。

I have a update form for users and would like to apply a custom validator on the password control.我有一个用户更新表单,并想在密码控件上应用自定义验证器。

Password value should either be blank or its minLength should be greater than 4.密码值应为空白或其minLength应大于 4。

To double check that other fields are not causing trouble I have assigned default values to other fields为了仔细检查其他字段是否没有造成问题,我已将默认值分配给其他字段

Form is initialised as shown below:表单初始化如下图:

this.updateUserForm = this.fb.group({
    first_name: ['John', [Validators.required]],
    last_name: ['Doe', [Validators.required]],
    email: ['test@email.com', [Validators.required]],
    password: ['', [UpdatePasswordValidator.validPasswordOrEmpty]],
});

Custom validator:自定义验证器:

import {FormControl} from '@angular/forms';

export class UpdatePasswordValidator {
    static validPasswordOrEmpty(fc: FormControl) {
        if (!fc.value || fc.value.length >= 4) {
            return null;
        }
        return ({validPasswordOrEmpty: true});
    }
}

Here is my html code, got rid of all other fields to debug.这是我的html代码,去掉了所有其他要调试的字段。

<ion-list lines="full">
    <form [formGroup]="updateUserForm" (ngSubmit)="onUpdate()">

        <ion-item>
            <ion-label position="fixed">Password</ion-label>
            <ion-input formControlName="password" type="password"></ion-input>
        </ion-item>

        <ion-row>
            <ion-col>
                <ion-button [disabled]="!updateUserForm.valid" color="primary" shape="full" type="submit"
                            expand="block">Update User
                </ion-button>
            </ion-col>
        </ion-row>
    </form>
</ion-list>

Following is edit.page.ts以下是edit.page.ts

export class EditPage implements OnInit {

    updateUserForm: FormGroup;
    id: any;
    errors = null;

    constructor(
        public route: ActivatedRoute,
        public fb: FormBuilder
    ) {
        this.id = +this.route.snapshot.params.id;
        this.updateUserForm = this.fb.group({
            password: ['', UpdatePasswordValidator.validPasswordOrEmpty],
        });
    }
}    

Created the above custom validator but it does not allow empty value.创建了上述自定义验证器,但它不允许空值。 when password value is blank updateUserForm.valid is always false.password值为空时, updateUserForm.valid始终为 false。

What am I doing wrong here?我在这里做错了什么?

Thank you谢谢

form can be invalid because other fields can be invalid. form可能无效,因为其他字段可能无效。 To verify if that particular control is valid or not, use this.updateUserForm.controls.passowrd.isValid;要验证该特定控件是否有效,请使用this.updateUserForm.controls.passowrd.isValid; Your custom validator function looks correct.您的自定义验证器 function 看起来正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM