简体   繁体   English

Angular 6模板驱动的表单添加带有条件的自定义验证

[英]Angular 6 template driven form add custom validation with condition

I am using template driven form in angular 6 . 我在angular 6使用template driven form

I added a custom validation named identityNumberValidator for identity number field that check if user typed correct identity number (IL identity) 我为身份编号字段添加了一个名为identityNumberValidatorcustom validation用于检查用户是否键入了正确的身份编号(IL身份)

The validation directive looks as bellow: 验证指令如下所示:

@Directive({
    selector: '[identityNumberValidator]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: IdentityNumberValidator,
            multi: true
        }
    ]
})
export class IdentityNumberValidator implements Validator {
    validator: ValidatorFn;

    constructor() {
        this.validator = this.identityNumberValidator();
    }

    validate(c: FormControl) {
        return this.validator(c);
    }


    identityNumberValidator(): ValidatorFn {
        return (c: FormControl) => {
            let isValid = true;
            if (c.value && c.value.length >= 9) {
                let idNum = c.value.padStart(9, '0');
                // CHECK THE ID NUMBER algoritm - http://halemo.net/info/idcard/
                let mone = 0;
                for (let i = 0; i < 9; i++) {
                    var incNum = idNum[i];
                    incNum *= (i % 2) + 1;
                    if (incNum > 9)
                        incNum -= 9;
                    mone += incNum;
                }
                if (mone % 10 !== 0) {
                    isValid = false;
                }
                else {
                    isValid = true;
                }
            }

            if (isValid == true) {
                return null;
            } else {
                return {
                    identityNumberValidator: {
                        valid: false
                    }
                };
            }
        }
    }

I Use it in my component for input element here: 我在这里将其用于输入元素的组件中:

<mat-form-field appearance="outline">
            <mat-label>מספר מזהה</mat-label>
            <input matInput
                   maxlength="9"
                   minlength="9"
                   required
                   identityNumberValidator
                   #identityNumberField="ngModel"
                   [(ngModel)]="identityNumber"
                   name="identityNumberField" />
            <mat-error *ngIf="identityNumberField.errors?.required">
              {{ eMessages.required}}
            </mat-error>
            <mat-error *ngIf="identityNumberField.errors?.minlength">
              יש להזין 9 ספרות
            </mat-error>
            <mat-error *ngIf="identityNumberField.errors?.identityNumberValidator">
              מספר זהות שגוי
            </mat-error>
          </mat-form-field>

My question is how can I use this validation with condition on other element? 我的问题是如何在其他元素上使用此验证条件?

I tried [identityNumberValidator] = "element == 1 ? '' : null" but does not work. 我尝试了[identityNumberValidator] = "element == 1 ? '' : null"但不起作用。 I read this post Angular conditional validation on template driven form 我读了这篇关于模板驱动形式的Angular条件验证的文章

but both [attr.identityNumberValidator] and [class.identityNumberValidator] does not work. 但是[attr.identityNumberValidator]和[class.identityNumberValidator]均无效。 The validation does not appear at all. 验证根本不会出现。

I know I can use reactive form but I do not want to. 我知道我可以使用反应形式,但我不想这样做。

So I can use two different input elements and use *ngIf between them but I want to find a solution to use only one element . 因此,我可以使用两个不同的输入元素,并在它们之间使用* ngIf,但是我想找到一种使用一个元素的解决方案。

Any Idea? 任何想法?

You can bind you custom function in the template driven approach, but that can be possible through @rxweb/reactive-form-validators. 您可以使用模板驱动的方法来绑定自定义函数,但是可以通过@ rxweb / reactive-form-validators进行绑定。

Here, I have used [compose] attribute on input filed where I have passed the validator method and set conditional expression. 在这里,我在通过验证器方法并设置条件表达式的输入字段上使用了[compose]属性。 See the code below: 请参见下面的代码:

[compose]="{validators:[identityNumberValidator.bind(this)],'conditionalExpression':'x => x.userName == \'Bharat\''}"

Here is the complete HTML. 这是完整的HTML。 where I have defined two control, 'userName' and 'firstName' the firstname validation will be fired once the 'userName' control value is 'Bharat'. 我定义了两个控件“ userName”和“ firstName”后,一旦“ userName”控件值为“ Bharat”,将触发名字验证。 See the below HTML code snippet. 请参见下面的HTML代码段。

  <div> <form #userinfoForm = "ngForm" [rxwebForm]="userinfoForm" [model]="userinfo"> <div class="form-group"> <label>User Name</label> <input type="text" name="userName" [(ngModel)]="userinfo.userName" class="form-control" /> </div> <div class="form-group"> <label>First Name</label> <input type="text" name="firstName" [(ngModel)]="userinfo.firstName" class="form-control" [compose]="{validators:[identityNumberValidator.bind(this)],'conditionalExpression':'x => x.userName == \\'Bharat\\''}"/> </div> <button [disabled]="!userinfoForm.valid" class="btn btn-primary">Submit</button> </form> </div> 

Here is the control custom method: 这是控件自定义方法:

  identityNumberValidator = (c: FormControl) => { let a = this; return {"msg":""}; } 

Stackbliz Example Stackbliz示例

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

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