我正在与Angular一起工作,试图弄清楚如何正确验证输入字段,并且该字段不应接受空格。我尝试使用 IF语句进行实验,如下所示。似乎工作正常,但是当一个输入字段为空时,我收到此错误消息:
错误TypeError:formValue.employee.trim不是函数
onSubmit() { //when the user clicks the submit button
const formValue = this.telephoneForm.value;
this.submitted = true;
if (this.telephoneForm.invalid) {
const invalidControls = this._findInvalidControls();
if (invalidControls.length) {
$("[formControlName=" + invalidControls[0] + "]").focus();
}
}
if (
this.telephoneForm.invalid ||
this.alreadyExist ||
this.noEmployeesFound ||
this.noDepartmentsFound ||
this.noVendorsFound
) {
return;
}
if (
(formValue["department"] === null ||
formValue["department"].trim() === "") ||
formValue["employee"] === null ||
formValue["employee"].trim() === "" ||
formValue["vendor"] === null ||
formValue["vendor"].trim() === ""
) {
$("[formControlName='department']").focus();
$("[formControlName='employee']").focus();
$("[formControlName='vendor']").focus();
this.noEmployeesFound = true;
this.noDepartmentsFound = true;
this.noVendorsFound = true;
return false;
}
}
答案 0 :(得分:0)
尝试一下。
3.8.0
答案 1 :(得分:0)
尝试一下对您有帮助
pattern: any;
ngOninit() {
this.pattern = "^\S{0,50}$";
//you can use this pattern to avoid space at beginning and end "^[^\s]+(\s+[^\s]+)*$"
this.telephoneForm = this.formBuilfer.group({
employee: [null, Validators.pattern(this.pattern), Validators.required ],
})
}
以上模式将不会在输入字段中接受空格,并在html中显示错误消息 像
<div *ngIf="employee.errors?.pattern">
employee is not valid.
</div>