Nenad Bulatović
Nenad Bulatović

Reputation: 7434

Angular 5 maxlength and alphanumeric validation

I am trying to display error if user input is not alphanumeric following this example, but without success. Error message is always displayed.

This is code snippet:

<div class="col-md-4" *ngIf="this.context.risk.contractOrigin === 'Appel_d_offre'">
    <label class="control-label" for="numberTenderInvitation">Numéro d'appel d'offre</label>
    <input class="form-control" id="numberTenderInvitation" name="numberTenderInvitation"
           [(ngModel)]="context.risk.policyId"
           #numberTender="ngModel"
           maxlength="10"
           [pattern]="'^[a-zA-Z \-\']$'"
           required/>
</div>
<small class="errorLabel" [hidden]="!numberTender.errors">
    Le champ comporte une erreur.
</small>

Error that I got is:

ERROR TypeError: Cannot read property 'errors' of undefined

Where did I go wrong?

Upvotes: 3

Views: 12435

Answers (4)

Oscar
Oscar

Reputation: 1

try with this.

      <small  [hidden]="numberTender.valid" class="errorLabel" >
         Le champ comporte une erreur.
      </small>

Upvotes: 0

Nenad Bulatović
Nenad Bulatović

Reputation: 7434

For the sake of reference I am posting final solution:

<div class="col-md-4" *ngIf="this.context.risk.contractOrigin === 'Appel_d_offre'">
    <label class="control-label" for="numberTenderInvitation">Numéro d'appel d'offre</label>
    <input class="form-control" id="numberTenderInvitation" name="numberTenderInvitation"
           #numberTender="ngModel"
           [(ngModel)]="context.risk.policyId"
           maxlength="10"
           [pattern]="'^[a-zA-Z0-9 \'\-]+$'"
    required/>
    <small class="errorLabel" [hidden]="numberTender.pristine || numberTender.valid">
        Le champ comporte une erreur.
    </small>
</div>

Upvotes: 2

Julian Hansen
Julian Hansen

Reputation: 61

Your pattern has a few problems

1. It is checking for a single character only
   ^ start of string
   [ ... ] match 1
   $ end of string
If you require at least one character you need to add a '+' if 0 or more a '*'

2. You say non-alphanumeric but you are not checking specifically for digits, you should add 0-9 to your pattern

3. Try moving your [\-] after the [\'] so your final pattern is as follows (assuming you want at least one char as input)

[pattern]="'^[a-zA-Z0-9 \'\-]+$'"

Upvotes: 6

Syntactic Fructose
Syntactic Fructose

Reputation: 20076

You're missing the elvis operator. This is required because your <small element is likely trying to access numberTender because it's been fully initialized. Try this:

<small class="errorLabel" [hidden]="numberTender?.errors">
    Le champ comporte une erreur.
</small>

I also removed the ! so this logic reads: If number Tender exists and it has an errors property

Upvotes: 1

Related Questions