【问题标题】:Angular pattern validation in HTML textareaHTML文本区域中的角度模式验证
【发布时间】:2020-03-20 09:12:59
【问题描述】:

我在 Angular 8 应用程序中使用 HTML 文本区域。我正在尝试使用正则表达式来验证文本区域中的输入,但不幸的是它不起作用。我在引导弹出窗口中使用 textarea 并在验证失败时禁用提交按钮。不幸的是,我没有使用反应式表单或模板驱动的表单。这是我的代码和我尝试过的:

<textarea id="reasonTex" rows="4" cols="64" [(ngModel)]="reason" (ngModelChange)='reasonChange()'
   [pattern]="reasonPattern" #rareason="ngModel">
</textarea>
<div *ngIf="rareason.errors.pattern"> 
    Reason not valid.
</div>  

TS:

reasonPattern = "^(?!\s*$).+";

【问题讨论】:

  • here
  • 你想用正则表达式准确地测试什么?
  • 嗨 Micheal,我想测试输入的第一个字符在 textarea 中是否为空
  • @YogeshMali:我已经发布了答案。请看看它是否适合你。

标签: javascript html angular


【解决方案1】:

正则表达式

要检查字符串的第一个字符是否不为空,可以使用表达式^\S.*$。表达式解释here.

打字稿

要根据正则表达式评估字符串,您可以使用test() 方法。它根据传递给它的参数返回一个布尔值。

现在我们有了正则表达式和在 Typescript 中测试它的方法,您只需要获取 textarea 中的文本输入,针对正则表达式进行测试并将按钮 [disabled] 属性绑定到它。

组件

export class NgbdModalContent {
  @Input() name;
  textAreaValue: any;
  enableSubmit = false;

  constructor(public activeModal: NgbActiveModal) {}

  onKeyUp(event: any) {
    this.enableSubmit = /^\S.*$/.test(this.textAreaValue);
  }
}

模板

<div class="modal-header">
  <h4 class="modal-title">Hi there!</h4>
  <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <textarea style="background-color:white;color:black;" [(ngModel)]='textAreaValue' (keyup)="onKeyUp($event)">                             
  </textarea>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" [disabled]="!enableSubmit" (click)="activeModal.close('Close click')">Submit</button>
</div>

工作示例:Stackblitz

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2019-03-30
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多