带有模式的 Angular Material url 验证

标签 angular typescript

你好,

我正在使用 Angular Material,我创建了一个表单字段,我想验证我的 url,但它不起作用。我尝试使用电子邮件,它正在工作。 我还希望在我输入有效的 url 之前禁用该按钮:

这是我的代码:

export class StartComponent implements OnInit {
  searchValue: string;
  url: any;
  public reg = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;

  constructor() {  }
  ngOnInit() {
    this.url = new FormControl('', [Validators.required, Validators.pattern(this.reg)]);
    this.getErrorMessage();
  }
  getErrorMessage() {
    return this.url.hasError('required') ? 'You must enter a value' :
        this.url.hasError('email') ? 'Not a valid url' :
            '';
  }
}

HTML

<mat-card class="searchbox">
    <mat-form-field>
        <input matInput placeholder="Enter your url" [formControl]="url" required>
        <mat-error *ngIf="url.invalid">{{getErrorMessage()}}</mat-error>
    </mat-form-field>
    <!--Here button should be disabled if url not valid and until there is something entered-->
    <button mat-stroked-button color="warn">GO</button>
</mat-card>

Here是 stackblitz 上的应用程序

最佳答案

像这样尝试:

DEMO

<mat-card class="searchbox">
    <mat-form-field>
        <input (focus)="markTouched()" matInput placeholder="Enter your url" [formControl]="url" required>
        <mat-error *ngIf="url.hasError('required')">
      Url required
    </mat-error>
    <mat-error *ngIf="url.hasError('pattern')">
      Url Pattern Invalid
    </mat-error>
    </mat-form-field>
    <!--Here button should be disabled if url not valid and until there is something entered-->

    <button [disabled]="url.invalid" mat-stroked-button color="warn">GO</button>
</mat-card>

{{url.errors | json}}

TS:

public myreg = /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi

  url = new FormControl('', [Validators.required, Validators.pattern(this.myreg)]);

 markTouched() {
    this.url.markAsTouched();
    this.url.updateValueAndValidity();
  }

关于带有模式的 Angular Material url 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52017171/

相关文章:

javascript - html存储safari隐身模式,angular2

node.js - 如何在浏览器关闭时让我的应用程序注销?

javascript - 'req'参数在哪里定义的?

reactjs - 如何使用 Typescript 的泛型将中继(graphql)连接映射到边缘节点

javascript - 使用 Decimal 库而不是 IEEE 754 数学的编译为 JavaScript 选项?

angular - 如何在 Angular 2 中创建一个数组或一组指令

Angular 构建配置 : add conditional file (robots. txt)

javascript - Angular 2 - 如果条件对于所有值都为真

angular - 如何检查字符串是否为 float/int 而不是 Angular8 中的 NaN?

javascript - 函数定义的下一个参数取决于第一个参数