0

I am trying to add regex to an input field in my angular app. The input field belongs to an HTML set which does not make use of a Form. The regex is to check that the input field is not empty. Is this possible to do? I would like to add it in my validateName function if possible.

Here is my code

HTML

<div>
  <div class="ui-g">
    <div class="tab-container">
      <div class="ui-g-12 ui-md-12">
        <strong style="padding-left:12px;">Template Name</strong>
      </div>
      <div class="ui-g-12 ui-md-12 ">
        <div class="input-container">
          <label for="jobTitle">Template name*</label>
          <input id="jobTitle" type="text" [disabled]="mode == 'view'" [(ngModel)]="templateName" size="100" (keyup)="validateName()">
        </div>
        <p class="error" *ngIf="!isValid">
          * An offer template with this name already exists.
        </p>
      </div>
  </div>
</div>

TS

validateName() {
    const regexBlankInput = "^\\s+$";
    if(this.templateName != '' ) {
      const found = this.usersService.allTemplates.some(x => x.name.toLowerCase() == this.templateName.toLowerCase());
      if ((found) || (this.templateName == regexBlankInput)) { 
      this.isValid = false;
      } else{
        this.isValid = true;
      }
    }  
}
6
  • 1
    Why don't you want to use forms? Commented Nov 18, 2019 at 11:51
  • An example using forms can be found here: concretepage.com/angular-2/… Commented Nov 18, 2019 at 11:54
  • I guess I'll try forms. I was just supposed to modify the code from another developer. Commented Nov 18, 2019 at 11:55
  • is there something not working with your code? Commented Nov 18, 2019 at 12:01
  • 1
    Just go with forms, they're designed for exact this use case. :) Commented Nov 18, 2019 at 12:10

1 Answer 1

1

You should go for Forms as how many validation method will you write for different field or same fields which needs different type of validations. ex: templatename if needs to check blank, trailing space,max length, special char etc.

But if you dont want to change existing architecture,

 var regex = /^\s+$/;   //got from here 
                        //https://stackoverflow.com/a/19121430/7562674
 var patt = new RegExp(regex);

 if(this.templateName != '' ) {
  var res = patt.test(this.templateName);   //true when it templateName is blank
  const found = this.usersService.allTemplates.some(x => x.name.toLowerCase() == 
  this.templateName.toLowerCase());
  if ((found) || res ) { 
  this.isValid = false;
  } else{
    this.isValid = true;
  }
} 

=> https://angular.io/guide/form-validation == Forms validation in angular.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.