下面的代码(forbiddenNames
方法)仅适用于区分大小写的代码。但我也想使其不区分大小写。如何使它工作?
例如
如果搜索文本“ ashutosh”(而不是“ Ashutosh”),那么它也应该能够在数组forbiddenUsernames
代码
模板:
<input type="text" id="username" class="form-control" formControlName="username">
班级
forbiddenUsernames = ['Chris', 'Ashutosh'];
ngOnInit() {
this.signupForm = new FormGroup({
'username': new FormControl(null, [Validators.required, this.forbiddenNames.bind(this)])
});
}
// validator is just a function, its our own validator
forbiddenNames(control: FormControl): {[s: string]: boolean} {
if (this.forbiddenUsernames.indexOf(control.value) !== -1 ) { // "-1" - did not find a match
return { 'nameIsForbidden' : true };
}
}
区分大小写
Case In-sensitive case
答案 0 :(得分:2)
您应该考虑使用禁止的名称来完成完整的大写或完整的小写。然后在比较时做有需要的事情;
类似的东西:
forbiddenUsernames = ['chris', 'ashutosh'];
ngOnInit() {
this.signupForm = new FormGroup({
'username': new FormControl(null, [Validators.required, this.forbiddenNames.bind(this)])
});
}
// validator is just a function, its our own validator
forbiddenNames(control: FormControl): {
[s: string]: boolean
} {
if (control.value && this.forbiddenUsernames.indexOf(control.value.toLowerCase()) !== -1) { // "-1" - did not find a match
return {
'nameIsForbidden': true
};
}
}
更新:
如果禁用名称列表来自数据库,则只需在列表上应用映射即可获取小写列表。
forbiddenNames = [
'John',
'JANE',
'jacob',
'SaM',
'JeReMy',
'sIdDhArTh'
];
forbiddenNames.map(name => name.toLowerCase());