【问题标题】:Angular Reactive Form Control numeric and Alphabetic pattern validator Validation not WorkingAngular Reactive Form Control 数字和字母模式验证器验证不起作用
【发布时间】:2020-08-15 15:42:54
【问题描述】:

我正在从动态 JSON 值创建一个自定义响应式表单,试图实现将用户在文本框中输入的字符隐藏为星号,

示例:假设用户正在输入“hello world”。

预期输出:**********,这应该在用户键入每个和 每个角色

还将进行模式验证,例如仅字母和仅数字,

我已达到上述预期输出,但验证未按预期工作

我尝试过的代码

 SetValidations(val: any) {
    this.formBuilder.control(val.key);
    this.newGeographyForm.addControl(
      val.key.toString(),
      new FormControl('')
    );
    let validators = this.getValidatorFnArray(val.templateOptions)
    debugger
    this.newGeographyForm.get(val.key).setValidators(validators)

    val.templateOptions.input_mask > 0 ?this.MaskValue(val.key,val.templateOptions.input_mask) : ''

  }
MaskValue(formControlVal:any,maskType:any){
    const regex = /\S/gi;
    const subst = `*`;
    this.newGeographyForm.get(formControlVal).valueChanges.pipe(distinctUntilChanged()).subscribe(fVal=>{
      const result = fVal.replace(regex, subst);
      this.newGeographyForm.get(formControlVal).patchValue( result, {emitEvent: false});
      this.newGeographyForm.get(formControlVal).updateValueAndValidity();
    })
  }

  getValidatorFnArray(obj): ValidatorFn[] {
    const validators = [];
    if (obj.is_mandatory) {
      debugger
      validators.push(Validators.required);
    }
    if (obj.min != null) {
      debugger
      validators.push(Validators.minLength(obj.min));
    }
    if (obj.max != null) {
      validators.push(Validators.maxLength(obj.max));
    }
    if (obj.regex != null) {
      validators.push(Validators.pattern(obj.regex));
    }
    return validators
  }

【问题讨论】:

    标签: angular angular-reactive-forms angular-validator


    【解决方案1】:

    我已经完成了类似的“从有效负载创建表单”的尝试,看起来添加验证器的逻辑非常合理,您可能希望为事物的模板端制作一些指示符,将其表示为隐藏字段,并动态显示。这样就可以用input type="password"处理了。

    编辑:

    听起来您想要做的是将值保存在 formControl 对象中,但让您的模板向用户显示不同的内容(****foo1,其中最后 4 个可见,其余为 *)

    这正是自定义 controlValueAccessor 实现所满足的角色。它是 html 表单字段元素与您用于存储/发送表单数据的实际表单模型之间的连接。

    我会调查一下,这有点令人困惑,但那里有一些可靠的教程/stackblitz 示例,可能需要一些挖掘。祝你好运!

    【讨论】:

    • 如果我使用密码,那么还有一个要求是只显示最后4个字符,其余的都是隐藏的,这不能通过输入密码来实现吗?。
    • 它不能。您可能处于需要自定义实现 controlValueAccessor 的情况:indepth.dev/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多