简体   繁体   中英

how to validate text in custom validate patterns using angular

I want to validate text only using this pattern ~*\\|:"<>?/ . Below is my textbox

<input type="text" [(ngModel)] ="newReferenceValue"  #referencevar="ngModel" name="referencevar" (keyup.enter)="save()" pattern='^[^`~!@#$%\^&*()_+={}|[\]\\:"]*$' style="margin: 8px;width: 60%;">

 <div *ngIf="referencevar.errors?.pattern">
         not valid not partens  
  </div>

You use this way

html

<input type="text" [(ngModel)] ="newReferenceValue"  #referencevar="ngModel" name="referencevar" (keyup.enter)="save()" [pattern]="pattern" style="margin: 8px;width: 60%;">

 <div *ngIf="referencevar.errors?.pattern">
         not valid not partens  
  </div>

ts

pattern = '^[^`~!@#$%\^&*()_+={}|[\]\\:"]*$';

However, the best way of using the patterns would be by using the reactive forms, you can refer this link for more understanding.

Here is an example that help you and if you have any query ask me in comments

    <form role="form" name="form" (ngSubmit)="f.form.valid" #f="ngForm" novalidate>

    <input type="text" id="newReferenceValue" name="newReferenceValue" [(ngModel)] ="newReferenceValue"  #referencevar="ngModel" pattern="^[^`~!@#$%\^&*()_+={}|[\]\\:"]*$" (keyup.enter)="save()" [ngClass]="{ 'is-invalid': f.submitted && referencevar.invalid }" style="margin: 8px;width: 60%;">

<div *ngIf="f.submitted && referencevar.invalid" class="invalid-feedback">

 <div *ngIf="referencevar.errors.pattern" class="error"> not valid not partens</div>
                                                                     </div>

    </form>

I'am using this Regex pattern ^[^~*\\\\|>:"?</"]*$ work fine

<input type="text" [(ngModel)] ="newReferenceValue"  #referencevar="ngModel" name="referencevar"  maxlength="{{textLengthValue}}" (keyup.enter)="save()" pattern='^[^~*\\|>:"?</"]*$' style="margin: 8px;width: 60%;">
 <div *ngIf="referencevar.errors?.pattern">
 Using ~*\|:"<>?/ reference value not applicabale  
 </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM