By default, numner input fields don't validate if the number entered manually by user is divisible by the step counter. If you want a feature like that, then you have to implement a custom validator which is pretty easy.
All you have to do is create a function to validate the number input field and then include the newly created validator in the Validators array of the FormControl object. Your validator function should either return a null value when your custom validation test passes or return a map of key-value pairs detailing the reason for failure.
Find the below code snippet demonstrating the use of custom validator to check if the current input value is a valid step or not.
export class AppComponent implements OnInit {
steps = 0.25;
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
numberControl: new FormControl(null, [
Validators.required,
this.validateNumField.bind(this)
])
});
this.myForm.valueChanges.subscribe(_ => {
if (!this.myForm.valid) {
console.log('err msg -> ', this.myForm.get("numberControl").errors);
}
});
}
validateNumField(control: AbstractControl): { [key: string]: any } {
let rem = control.value && Number.parseFloat(control.value) % this.steps;
// console.log(rem);
/**
* If the remainder is not 0 then user has entered an invalid value
*/
return rem ? { error: "Not a valid step" } : null;
}
}
Now your submit button will not work if it is not a valid step. You can go ahead and show an error message on the template if you want using this.myForm.get("numberControl").errors property.
You can find an working example in stackblitz here. For more on custom validation, visit Angular docs.
Edit: Updated answer to capture change in steps value.