【问题标题】:Angular 6 template driven form add custom validation with conditionAngular 6模板驱动表单添加带有条件的自定义验证
【发布时间】:2019-06-26 07:33:08
【问题描述】:

我在angular 6 中使用template driven form

我为身份号码字段添加了一个名为 identityNumberValidatorcustom validation,用于检查用户是否输入了正确的身份号码(IL 身份)

验证指令如下所示:

@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
                    }
                };
            }
        }
    }

我在我的组件中使用它作为输入元素:

<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>

我的问题是如何在其他元素上使用此验证条件?

我试过[identityNumberValidator] = "element == 1 ? '' : null" 但不起作用。我读了这篇文章 Angular conditional validation on template driven form

但是 [attr.identityNumberValidator] 和 [class.identityNumberValidator] 都不起作用。验证根本不出现。

我知道我可以使用反应形式,但我不想。

所以我可以使用两个不同的输入元素并在它们之间使用 *ngIf 但我想找到一个解决方案来使用只使用一个元素

有什么想法吗?

【问题讨论】:

  • 您能添加您的验证器代码吗?
  • 阅读一些例子here
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself :请提供minimal reproducible example。至于您的问题,请至少提供一些代码,以了解您是否关注了documentation(如果没有,请关注它)
  • 另一个使用指令验证模板驱动表单stackoverflow.com/questions/56716216/… 的示例。它只是创建一个实现 Validator 的指令,它有一个提供者 providers: [{ provide: NG_VALIDATORS, useExisting: RepeatNameDirective, multi: true }] 并使用 @Input 来获取参数
  • 嗨,我添加了示例代码

标签: angular validation


【解决方案1】:

您可以在模板驱动的方法中绑定自定义函数,但这可以通过@rxweb/reactive-form-validators 实现。

在这里,我在输入字段上使用了[compose] 属性,其中我通过了验证器方法并设置了条件表达式。请看下面的代码:

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

这是完整的 HTML。我已经定义了两个控件,“userName”和“firstName”,一旦“userName”控件值为“Bharat”,名字验证将被触发。 请参阅下面的 HTML 代码 sn-p。

    <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>

这里是控件自定义方法:

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

Stackbliz Example

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多