I have the following code for demo purposes, showing a simple form row with error messages and a submit button:
<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>
where tidDigits
is a custom ValidatorDirective with this 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;
};
}
I want the demo to show the different error messages when the user clicks the submit button. For this is a demo form, I do not want the form to submit at all.
The error messages show up correctly (after pressing the submit button) when the field is empty (required
-Validator) or e.g. 20,44 is entered (tidDigits
-Validator). However, if a valid value is entered (e.g. 20,4), the form submits - i.e. the page is reloaded and the field name is appended to the URL: /tid-form-row?temperatureName=20,4
Is there any way to prevent a form from submitting at all?
I tried (ngSubmit)="onSubmit()"
with onSubmit() { return false; }
and also (ngSubmit)="$event.preventDefault()"
as stated here, but it did not work. Any other ideas?