Home > Blockchain >  Check regex validation using nativeElement in Angular
Check regex validation using nativeElement in Angular

Time:10-21

I am trying to validate input for which I am using pattern. I have used the pattern on input in HTML and want to further check whether the user input is valid using the nativeElement property of ElementRef. Can anybody tell me how can I do that?

Here's my code:

HTML

 <input #password
  pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_= -]).{8,}$" 
  type="password" value="" 
  name="password"/>
  <button type="submit" (click) = "validate()">Submit</button>

TS

@ViewChild('password', {static: false}) password: ElementRef;
validate()
{
   if(this.password.nativeElement.valid)   //how can I check input validity here
   //do something 
}

CodePudding user response:

Well, here (by using ViewChild) You're grabing ElementRef of 'HtmlInputElement', which, obviously, doesn't have 'valid' prop ('valid' - it's from ng's Forms' Control, so You could use Forms/ReactiveForms module to have all the sugar from it)... To use the api/code as above, You could have something like:

  @ViewChild('password', { static: false }) password: ElementRef<HTMLInputElement>;

  validate() {
    if (this.password.nativeElement.validity.valid) {
      console.log('valid'); /// 'kAAzkf==09@A!102-   ==> prints 'valide'
    } else {
      console.log('invalid');
    }
  }
  • Related