Panadol Chong
Panadol Chong

Reputation: 1903

angular text box avoid only 1 special character

Good day,

I have a requirement which is only need to not allow only 1 special character for user input, which is ~. The following is my code:

<div class="form-input ">
          <input class="pass" [type]="'password'" name="newPassword"
            placeholder="New Password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#&()-/$=<>?]).*$" #newPassword="ngModel"
            [(ngModel)]="newPassword" (ngModelChange)="checkNewPassword()"
            (click)="onInputFocus()" minlength={{changePasswordFormCriteria.minPwrdLength}}
            maxlength=30 (blur)="checkNewOldPassVal()">
          </div>
        </div>

<div *ngIf="newPassword.errors?.pattern && loginPasswordForm.submitted" class="form-errors">
          New Password must consist at least one uppercase, one lowercase letter, one number and one special characters within this range ! @ # & ( ) - ? / $ = < >
        </div>

As you can see, I exclude the ~ character from the pattern. This is work if I only key in only 1 special character ~, for example, "password~abc", this will prompt the error message in newPassword.errors?.pattern. This is correct and this is match with requirement.

However, if I include other special character, for example, I key in "password@~abc", this will not prompt error message, it will allow to go through. I am wondering I not include the ~ in the pattern, but not sure why it still can pass through.

May I know what mistake I did?

Upvotes: 0

Views: 2254

Answers (1)

joohong89
joohong89

Reputation: 1271

The expression you have used only make sure that the string input contains the expression provided. It does not enforce the exclusion of ~ from the input.

You may want to try this instead

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#&()\-/$=<>?])[a-zA-Z0-9!@#&()\-/$=<>?]+$

One more thing, in this part of your regex

...[!@#&()-/$=<>?]...

You got to delimit the hyphen(-), else it will allow characters ranging from ascii 41-47. It should look something like this

...[!@#&()\-/$=<>?]...

Or simply add the hyphen to the beginning or end as @Cary had pointed out.

Upvotes: 1

Related Questions