0
votes

Am creating a custom reactive form from dynamic JSON value, trying to achieve hide the character what the user entered in text box to asterisk symbol,

Example: lets say user is typing "hello world".

Expected output: **********, this should come when user types each and every character

there will be also pattern validation like alphabet only and number only,

I have achieved the above Expected Output, but the validation is not working as expected

Code What i have Tried

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

1 Answers

0
votes

I've done similar 'create form from payload' endeavors, it looks like the logic for adding validators is pretty sound, you may want to make some indicator for the template side of things that denotes it as a hidden field though, and dynamically show it. That way it can all be handled with input type="password".

EDIT:

It sounds like what you want to do is hold the value within the formControl object but have your template display something different to the user (****foo1, where the last 4 are visible the rest are *)

This is the exact role a custom controlValueAccessor implementation satisfies. It is the connection between the html form field element and the actual form model you are using to store/send form data.

I'd look into it, it's a bit confusing but there are some solid tutorials/stackblitz examples out there, may just take some digging. Best of luck!