angular: required validator does not work with number
The required validator does not work with a input whose type is number :
<input type="number" ngControl="weight" />
this.form = fb.group({
weight: ["", Validators.required]
});
When the input is empty, no error appear.
The reason is that the NumberValueAccessor selector match the input, and set the value of the Control to a number. If the entered string of the input does not match a number, the value is NaN. This is the case for the empty string. But the required validator return a error only if the control value is blank (null or undefined) or is a empty string. This is not the case of any of these two conditions because the NumberValueAccessor set the value to the NaN number.
The required validator can not really verify the NaN value because it can appear for empty string, but also for string that are not a number (like ‘aaa’). The problem is that the validator can not retrieve the entered string from the control variable.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 1
- Comments: 22 (5 by maintainers)
Links to this issue
Commits related to this issue
- fix(forms): number inputs should report null when blank Closes #6932 — committed to kara/angular by kara 8 years ago
- fix(forms): number input should report null when blank Closes #6932 — committed to kara/angular by kara 8 years ago
- fix(forms): number input should report null when blank Closes #6932 — committed to angular/angular by kara 8 years ago
@fredgate 0.0 sounds good to me as well! I could update the fix inside the PR to support that, but let’s hear from angular team first @pankajparkar yes, you’re right, but that is not a problem since it is parsing to Float, the parseFloat supports
2e2
that would return200
after parsed for example. The problem is when the user typese2
it is aNaN
after parsed. For this case I think required validator should not returnrequired
error, because there is an information inside the field. Whether that information is invalid or not, required validator shouldn’t care in my opinion. That is another type of validation. The current problem is when user touches the field, and then leave it blank.ControlValueAccessor
receives empty string form the dom element, which leads toNaN
, but in this case I thinkNaN
is not appropriate because user hasn’t provided any value to the input field, thereafter it should be faced as empty (eithernull
or0
) rather thanNaN
.