Q:

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?

A:

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 \'\-]+$'"

