How to remove code repetition in Angular for a method that validates form fields

44 Views Asked by At

I have a form that when user types a number below 0.001 an error message will appear for all the properties except test4.

For test4 I use getValidationTwo that checks if user typed a number below 1 and if he did, display a different warning message.

My code works fine as it is.

My question is, that if there is a solution to not repeat my code and use one method for all the form properties.

 ngOnit(): void {
      this.myForm = new UntypedFormGroup({
      test1: this.getValidation(),
      test2: this.getValidation(),
      test3: this.getValidation(),
      test4: this.getValidatioTwo(),
    })
    }
    
    getValidation() = (value?: number) => {
    const test = new UntypedFormControl(value != null ? value: '', {updateOn: 'blur', validators:Validators.required, Validators.min(0.001),]})
    control.valueChanges.subscribe(() => {
      if(test.invalid && test.error.min && test.dirty) {
         this.display.Error(Message.NEGATIVE_NUM);
    }
    })
     return test
    }
    
    getValidationTwo() = (value?: number) => {
    const test = new UntypedFormControl(value != null ? value: '', {updateOn: 'blur', validators:Validators.required, Validators.min(1),]})
    control.valueChanges.subscribe(() => {
      if(test.invalid && test.error.min && test.dirty) {
         this.display.Error(Message.NO_ONE);
    }
    })
     return test
    }
1

There are 1 best solutions below

0
On

As i see in your code, only the value of the validation field in your "test" const changes. So, i would guess you can juste create a general getValidation() with a parameter value and a parameter validator where you would specify the Validators specifically.