1
votes

so I'm trying to display different validation messages depending on the validator on my form control.

Here's what I have set up so far:

this.Form = fb.group ({
      'FooNumber': [null, Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9\\-_]*$')])]
    });

In my html:

<input formControlName="FooNumber" (blur)="NoSpecialCharacters && !this.Form.get('FooNumber').valid" [ngClass]="!this.Form.get('FooNumber').valid ? 'inputRed': 'input'"/>

<div class="error-msg" *ngIf="!this.Form.get('FooNumber').valid" name="errorMsg"> This is a required field </div>

<div class="error-msg" *ngIf="NoSpecialCharacters && !this.Form.get('FooNumber').valid" name="errorMsg">Enter a valid number </div>

My question is, I want to show the message with ngIf "NoSpecialCharacters" for the Regex in the Validators.pattern() above but if the field was felt empty and user clicked on submit, it should show the other message , "Required field" message.

I was wondering, what's the best approach to having different error messages display depending on which validator goes off.

Do I need to create a custom validator to handle this scenario?

1
Instead of checking FormControl.valid, inspect FormControl.errors. Different validators will add different errors to that object, and you can base your condition on that to display different error messages.Harry Ninh
Will FormControl.errors include the regex pattern error and the required error or just the regex pattern error? I was thinking if there was still a way to differentiate between them. Thanks!Techno_Wizard

1 Answers

2
votes

Try this to improve your validation

Always keep the validation control at backend if you are using ReactiveForms as shown below.

component.ts

  unamePattern = "^(?=.*[a-z]).{2}[a-zA-Z0-9\\-_]*$";

  isValidFormSubmitted = null;

  Form = this.formBuilder.group({
    FooNumber: ['', [Validators.required, Validators.pattern(this.unamePattern)]]
  });

  constructor(private formBuilder: FormBuilder) {

  }

  onFormSubmit() {
     this.isValidFormSubmitted = false;
     if (this.Form.invalid) {
        return;
     }
     this.isValidFormSubmitted = true;
     this.Form.reset();
  }

  get FooNumber() {
     return this.Form.get('FooNumber');
  }

component.html

<h3>Add Form</h3>
<p *ngIf="isValidFormSubmitted && Form.pristine" [ngClass] = "'success'">
    Form submitted successfully.
</p>
<form [formGroup]="Form" (ngSubmit)="onFormSubmit()">
 <table>
  <tr> 
    <td>User Name: </td>
    <td> 
        <input formControlName="FooNumber">
        <div *ngIf="FooNumber.errors && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass] = "'error'"> 
            <div *ngIf="FooNumber.errors.required">
                This is a required field.
            </div>  
            <div *ngIf="FooNumber.errors.pattern">
                Enter a valid number.
            </div> 
        </div>
    </td>
  </tr> 
  <tr>    
    <td colspan="2">
        <button>Submit</button>
    </td>
  </tr>    
 </table>  
</form>

Demo

I hope this will help you to improve your validation on forms. If you have any issues or doubt let me know.