要实现这个功能,我们可以利用Angular的自定义验证器来创建一个只允许第一行没有特殊字符的验证器。下面是一个例子:
首先在组件类中创建验证器:
import { FormControl, ValidatorFn, Validators } from '@angular/forms';
export const forbiddenFirstCharValidator: ValidatorFn = (control: FormControl) => {
const forbidden = /^\s*[\!\@\#\$\%\^\&\*\(\)\+\=\[\]\{\}\\\|\;\:\'\"\,\.\<\>\/\?]\s*/.test(control.value.split('\n')[0]);
return forbidden ? { 'forbiddenFirstChar': true } : null;
};
接着,在表单中使用验证器:
The first line cannot start with a special character!
最后,为表单控件添加验证器:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { forbiddenFirstCharValidator } from './forbidden-first-char.validator';
@Component({
selector: 'my-component',
template: `
`,
})
export class MyComponent {
myForm = new FormGroup({
'myTextArea': new FormControl('', [
Validators.required,
forbiddenFirstCharValidator
]),
});