beginerdeveloper
beginerdeveloper

Reputation: 845

validate form with single message

Here is my Code and so have many fields like this :

<input type="text" pInputText class="form-control" name="companyName" [(ngModel)]="company.Name" required #companyName="ngModel"
      />
      <label>Company Name</label>
      <p class="ui-message ui-messages-error ui-corner-all" *ngIf="(!companyName.valid && companyName.touched)">
         Company Name is required
      </p>

Instead of defining separate message for all mandatory/invalid fields, can't I use single message with place holder for field name? So whenever I want to change message, I can manage this with single line change.

e.g. "${field} is required, ${field} is not valid etc."

please give me a example if this can do

Upvotes: 0

Views: 52

Answers (1)

DobleL
DobleL

Reputation: 3928

The first solution that crossed my mind was just wrap the error messages in a function:

var displayError = (field) => `${filed} is required`;

And on the HTML

<input type="text" pInputText class="form-control" name="companyName" [(ngModel)]="company.Name" required #companyName="ngModel"/>

  <label>Company Name</label>
  <p class="ui-message ui-messages-error ui-corner-all" *ngIf="(!companyName.valid && companyName.touched)">
     {{ displayError('Company name') }}
  </p>

Upvotes: 1

Related Questions