1

I am developing job form which contains job related fields and some of the fields have more than 5 validation.

Here is my Html Code:

<div [formGroup]="jobForm">
  <div>
<input type="text" formControlName="userName"/>
    <div *ngIf="jobForm.controls.userName.errors && jobForm.controls.userName.errors.required"
    class="alert alert-danger">
      Required....
    </div>
    <div *ngIf="jobForm.controls.userName.errors && jobForm.controls.userName.errors.maxLength"
    class="alert alert-danger">
      max length 10
    </div>
    <div *ngIf="jobForm.controls.userName.errors && jobForm.controls.userName.errors.exits"
    class="alert alert-danger">
      user is already exits
    </div>
    <div *ngIf="jobForm.controls.userName.errors && jobForm.controls.userName.errors.shouldNotSameAsName"
    class="alert alert-danger">
      Should Not Same as name.
    </div>
    <div *ngIf="jobForm.controls.userName.errors && jobForm.controls.userName.errors.minLength"
    class="alert alert-danger">
      minimum length is 5
    </div>
</div>
  

In my job form there are more than 15 fields in one wizard, It is bit difficult to manage the code on HTML side with *ngIf conditions. How can I overcome this problem?

See the below link, which is little bit same as mine but it is not marked as answer and not found any documentation on the provided answer.

Best way to show error messages for angular reactive forms, one formcontrol multiple validation errors?

Thanks in advance.

Ami Vyas
  • 119
  • 2
  • 9

1 Answers1

0

Someone has answered this question and my issue was resolved with the provided answer. But that has been removed, I don't know why.

I have used @rxweb/reactive-form-validators for showing error message without *ngIf.

I have used 'RxFormBuilder' to create a FormGroup object and used errorMessage property of FormControl. Below is the TS code which I have downloaded form the provided answer:

export class AppComponent  {

  userFormGroup:FormGroup;

 

  constructor(private formBuilder:RxFormBuilder){}

 

 

  ngOnInit(){

  //this is used for to configure validation message globally. https://www.rxweb.io/api/reactive-form-config

    ReactiveFormConfig.set({

     "validationMessage":{

    "required":"This field is required",

      "minLength":"minimum length is {{0}}",

      "maxLength":"allowed max length is {{0}}"

      }

    });

 

    this.userFormGroup = this.formBuilder.group({

     userName:['',[RxwebValidators.required(),RxwebValidators.minLength({value:5}),RxwebValidators.maxLength({value:10})]]

    })

  }

Html Code :

<form [formGroup]="userFormGroup">

<div class="form-group">

    <label>UserName</label>

    <input type="text" formControlName="userName" class="form-control"  />

    {{userFormGroup.controls.userName["errorMessage"]}}

 

</div>

</form>
Ami Vyas
  • 119
  • 2
  • 9