简体   繁体   English

Angular 4和打字稿

[英]Angular 4 and typescript

i need to validate the textbox which is present in form where i dont want user to enter the spaces initially and it should start with alphanumeric and then we can add spaces in between the text. 我需要验证文本框,该文本框以我不希望用户最初输入空格的形式存在,它应以字母数字开头,然后我们可以在文本之间添加空格。

i am writing the regex code in typescript but it is not working for me. 我在打字稿中写正则表达式代码,但对我不起作用。

i am calling allowAlphaNumeric method on keypress in input control 我在输入控件中的按键上调用allowAlphaNumeric方法

allowAlphaNumeric(event) {
        return event && event.key && event.key.match(this.regExpAlphaNumeric) ? true : false;
    }

<input class="form-control ip-box-css" type="text" formControlName = "campaignName" id="campaignName" (keypress)="allowAlphaNumeric($event)" maxlength="30" placeholder="Enter" required>

where regExpAlphaNumeric: string = '^[^-\s][a-zA-Z0-9_\s-]+$';

the issue is that the regex expression is not considering as string 问题是正则表达式未考虑为字符串

Please provide some suggestion so that it will work in .ts(typescript) file 请提供一些建议,以便它可以在.ts(typescript)文件中使用

Create a form control (or a control in a formGroup) 创建一个表单控件(或formGroup中的控件)

textboxToValidate: FormControl = new FormControl('', [
  Validators.required,
  Validators.pattern(/^[^-\s][a-zA-Z0-9_\s-]+$/)
]);

Those built-in classes can be imported from the form module 这些内置类可以从表单模块中导入

import { FormControl, Validators } from '@angular/forms';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM