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)

Commits related to this issue

Most upvoted comments

@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 return 200 after parsed for example. The problem is when the user types e2 it is a NaN after parsed. For this case I think required validator should not return required 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 to NaN, but in this case I think NaN is not appropriate because user hasn’t provided any value to the input field, thereafter it should be faced as empty (either null or 0) rather than NaN.