Home > Software engineering >  Conditional validation for Username or Email input field in Angular
Conditional validation for Username or Email input field in Angular

Time:03-30

I must create an input field where a user must enter either username or email and I must use conditional validation, if @ is entered, it must check for email validation, if its not it checks for the username(username must contain only english letters and numbers). So my question is, is there any regex pattern that could solve this?

here is my code so far:

\<label  for="usernameEmail"\>Username or email address\</label\>
\<input id="usernameEmail" type="text" name="usernameEmail"  ngModel required
pattern="" #usernameEmail ="ngModel"\>
\</div\>

I am using Template Driven Form

Any kind of help is welcome and thanks in advance.

CodePudding user response:

This should do it - just switch the regex based on your condition

<input
  id="usernameEmail"
  type="text"
  name="usernameEmail"
  
  ngModel
  required
  [pattern]="usernameEmail.value?.includes('@') ? 'email regex' : 'username regex'"
  #usernameEmail="ngModel"
/>
  • Related