1

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?

2
  • 2
    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. Commented Apr 5, 2018 at 2:49
  • 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! Commented Apr 5, 2018 at 3:17

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think the Stackbiltz link doesn't work. Can you double check? Otherwise, I will work off the code in the post. Thanks a lot for your help!
@Techno_Wizard can you check now. sorry for inconvenience.
@Techno_Wizard If you are satisfied with my answer, then mark it as correct. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.