How can I validate an input of type="number"
to only be valid if the value is numeric or null using only Reactive Forms (no directives)?
Only numbers [0-9]
and . are allowed, no "e" or any other characters.
What I've tried so far:
Template:
<form [formGroup]="form" novalidate>
<input type="number" formControlName="number" id="number">
</form>
Component:
export class App {
form: FormGroup = new FormGroup({});
constructor(
private fb: FormBuilder,
) {
this.form = fb.group({
number: ['', [CustomValidator.numeric]]
})
}
}
CustomValidator:
export class CustomValidator{
// Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
if (val === null || val === '') return null;
if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };
return null;
}
}
Plunker
The problem is when a user enters something that is not a number ("123e" or "abc") the FormControl's value becomes null
, keep in mind I don't want the field to be required so if the field really is empty null
value should be valid.
Cross browser support is also important (Chrome's number input fields do not allow the user to input letters - except "e", but FireFox and Safari do).
type="text"
totype="number"
. I don't understand why Angular changes the control's value, but doesn't do anything to validity. Seems like a bug to me.ControlValueAccessor
to overcome this behavior. I already have a custom date control that does something similar to store an ISO compliant date string in the form's value instead of the "10/16/2018" string that is displayed in the input. I'll add my solution here once I get to the bug regardingtype="number"
sometime this month hopefully.