我正在使用ngx-chips将电子邮件列表作为标签添加到输入中。验证器确保每个标签看起来像一封电子邮件。
我如何确保:
1)验证器仅在添加标签时触发(例如,用户按enter、空格或逗号)
2)如果在按enter/空格/逗号时电子邮件无效,则该值仍然存在(即,用户可以修复该值并不clear...so )
堆栈闪电战来了:https://stackblitz.com/edit/ngx-chips-example-2qdudc
下面是我的电子邮件验证器:
public validators = [ this.must_be_email ];
public errorMessages = {
'must_be_email': 'Please be sure to use a valid email format'
};
private must_be_email(control: FormControl) {
var EMAIL_REGEXP = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/i;
if (control.value.length != "" && !EMAIL_REGEXP.test(control.value)) {
return { "must_be_email": true };
}
return null;
}下面是标签:
<tag-input [(ngModel)]='emails'
name="emails"
#email="ngModel"
[errorMessages]="errorMessages"
[validators]="validators"
[editable]='true'
(onTagEdited)="onTagEdited($event)"
[separatorKeyCodes]="[32,188,186,13,9]"
[placeholder]="'Add email'"
[secondaryPlaceholder]="'Enter email address(es)'"
[clearOnBlur]="true"
[addOnPaste]="true"
[addOnBlur]="true"
[pasteSplitPattern]="splitPattern"
theme='bootstrap'
required >
</tag-input>对于2),我尝试在validator...but中将"return null“更改为control.value,但没有起作用
发布于 2019-03-04 07:44:08
ngx芯片有一个事件onAdding,你可以用它来做额外的检查。在事件处理程序中,您可以检查组件是否有效,如果控件无效,则取消添加。那么文本就会留下来。对于Enter键,它不能工作,因为Enter键被编码为提交表单,并且总是清除文本。您可以在标记输入内部使用的GitHub source code of the tag-input-form component中看到它。检查onKeyDown方法。
以下是组件中onAdding处理程序的示例实现:
public onAdding(tag): Observable<string> {
if (!this.hasErrors()) { // this is tricky the this here is actually the ngx-chips tag-input component
return of(tag);
} else {
return EMPTY;
}
}正如我已经在代码的注释中提到的,由于事件处理程序的调用方式,函数内部的this实际上是ngx-chip标签输入组件,而不是您通常期望的组件。
有了这个方法后,您只需将其绑定到模板中,它就应该可以工作了。
<tag-input ... [onAdding]="onAdding">我还用这个实现创建了一个fork of your stackblitz。
如果这不起作用,您可能需要联系组件的作者以获取更多详细信息,或者使用其他组件。例如,角度材质组件包含一个类似的chip input component。
https://stackoverflow.com/questions/54877393
复制相似问题