【问题标题】:Add regex to an input field without using Form在不使用表单的情况下将正则表达式添加到输入字段
【发布时间】:2020-03-13 18:46:10
【问题描述】:

我正在尝试将正则表达式添加到我的 Angular 应用程序的输入字段中。输入字段属于不使用表单的 HTML 集。正则表达式是检查输入字段是否为空。这可能吗?如果可能的话,我想将它添加到我的 validateName 函数中。

这是我的代码

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;
      }
    }  
}

【问题讨论】:

  • 为什么不想使用表单?
  • 可以在此处找到使用表单的示例:concretepage.com/angular-2/…
  • 我想我会试试表格。我只是应该修改另一个开发人员的代码。
  • 您的代码是否有问题?
  • 只需使用表单,它们就是为这个用例而设计的。 :)

标签: angular


【解决方案1】:

您应该选择表单,因为您将为需要不同类型验证的不同字段或相同字段编写多少验证方法。例如:如果需要检查空白、尾随空格、最大长度、特殊字符等的模板名称。

但是如果你不想改变现有的架构,

 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 == Angular 表单验证。

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 2020-01-03
    • 2020-08-09
    • 2021-07-13
    • 2020-06-12
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多