2

Is there a way to use browser's native HTML validation error messages and use them in angular way?

what I would like is to when having like a reactive form like this:

testForm: FormGroup = this.fb.group({
  postCode: [{ value: 'postcode', disabled: true }],
  name: ['John'],
  city: [{ value: 'London', disabled: false }, [Validators.required, Validators.minLength(3)]],
});

to be able to use the native error messages in the form like:

<form [formGroup]="testForm" #myForm="ngForm">
  <input type="text" formControlName="city" >
  <div class="errors">
    <p *ngFor="let errorCode in myForm.controls.city.errors">
      {{ getBrowserNativeErrorMessage(errorCode) }}
    </p>
  </div>
</form>
TylerH
  • 20,799
  • 66
  • 75
  • 101
DS_web_developer
  • 3,622
  • 13
  • 52
  • 83

1 Answers1

2

You can use ngNativeValidate attribute in the form tag

<form ngNativeValidate>
</form>

But I don't think Reactive form Validators will work with this, you will have to use html native validation attributes

<input type="text" minlength="3" required>
YogendraR
  • 2,144
  • 12
  • 17
  • yeah, I would like it to work both ways... especially reactiveForms way... and also I would like better control of it... maybe get the array of messages or object, so I can show the messages the way I want – DS_web_developer Oct 11 '21 at 13:22
  • You can try Angular Material, it provides in built features that works smoothly with reactive forms – YogendraR Oct 11 '21 at 13:43
  • Hmm... where? could you please point me to where I can harness the native error messages via ng material? I am using it but cannot find this functionality there – DS_web_developer Oct 11 '21 at 13:58
  • check [this](https://material.angular.io/components/form-field/overview#form-field-error), if this can help – YogendraR Oct 11 '21 at 14:05
  • that does not help me... this is what I am actually using to display the error messages... but this is just presentation... there is no actual business logic there... you need to build one yourself (checking if input is invalid and the cycle through control's errors... but you wouldn't get any error msg strings from there... unless you set them yourself – DS_web_developer Oct 11 '21 at 14:13