gpt4 book ai didi

angular - 在 Angular 5 中验证后防止提交表单

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:36 24 4
gpt4 key购买 nike

我有以下用于演示目的的代码,显示带有错误消息和提交按钮的简单表单行:

<form [ngFormOptions]="{updateOn: 'submit'}">
<tid-form-row>
<label tid-ui-label for="temperatureInput">Temperature:</label>
<input [tid-ui-input]="{required: true}" id="temperatureInput" name="temperatureName" placeholder="20,4"
[(ngModel)]="temperatureModel" #temperature="ngModel" [tidDigits]="{integer: 2, fraction: 1}" required>
<ng-template #hint>
<small tid-ui-hint>The yellow color indicates that this field is required.</small>
</ng-template>
<div tid-ui-error *ngIf="temperature.invalid && (temperature.dirty || temperature.touched); else hint">
<span *ngIf="temperature?.errors.required">Field is required.</span>
<span *ngIf="temperature?.errors.tidDigits">Must be max 2 integer digits and max 1 fraction digit.</span>
</div>
</tid-form-row>
<tid-button type="submit">Check validation</tid-button>
</form>

其中 tidDigitscustom ValidatorDirective使用此 ValidatorFactory:

export function digitsValidator(config: any): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const value = control.value;
const errorObject: any = {tidDigits: {value: control.value}};
let passed = true;

if (value) {
const [integer, fraction] = value.split(',');
if (config.integer && config.integer >= 0) {
if (integer.length > config.integer) {
passed = false;
errorObject.tidDigits.integer = integer.length;
}
}
if (config && config.fraction && config.fraction >= 0) {
if (fraction.length > config.fraction) {
passed = false;
errorObject.tidDigits.fraction = fraction.length;
}
}
}
return passed ? null : errorObject;
};
}

我希望演示在用户单击提交按钮时显示不同的错误消息。因为这是一个演示表单,我根本不想提交表单。

当字段为空(required-Validator)或例如输入 20,44(tidDigits-Validator)。但是,如果输入了有效值(例如 20,4),表单会提交 - 即重新加载页面并将字段名称附加到 URL:/tid-form-row?temperatureName=20,4

有什么方法可以完全阻止表单提交吗?

我尝试使用 (ngSubmit)="onSubmit()"onSubmit() { return false; }(ngSubmit)="$event.preventDefault()"here 所述, 但它没有用。还有其他想法吗?

最佳答案

<button> 中 type 属性的默认值标签是 submit ,如果你想防止这种情况发生,你需要覆盖它:

<button type="button"></button>

删除 type="submit"还不够,这里有更多详细信息:HTML button to NOT submit form


如果你仍然想验证,也许你可以尝试以下方法:

<form #form>
<button type="button" (click)="validateForm(form)"></button>
</form>

并且,在您的 Typescript 代码中:

public validateForm(form: NgForm) {
for (const control in form.controls) {
control.updateValueAndValidity();
}
}

关于angular - 在 Angular 5 中验证后防止提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48080906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com