Skip to content

toNumber is lenient #2598

@jods4

Description

@jods4

Version

3.0.2

Steps to reproduce

toNumber (defined in @vue/shared) uses parseFloat, which is very lenient and will succeed if the first non-whitespace character is a digit (or sign).

So toNumber("1234abc") will succeed and return 1234.

toNumber is used by the .number modifier, so this surfaces in very observable ways to the end-user.

A simple alternative would be Number("1234abc"), which does fail if the complete string isn't a valid number. Like parseFloat it does accept spaces at the beginning and end of string.

What is expected?

<input v-model.number="x" />

If I input "12abc", given the behavior of v-model.number, I expect x to be the string 12abc, which can then be handled as a validation error in user code.

What is actually happening?

12 is assigned to x.

EDIT Another defect caused by this implementation is that a textbox is not stable and its content changes unexpectedly for the end user.
If you have a textbox <input v-model.number=x> and type abc123, then the text stays the same when the component is updated. But if you type 123abc then the content is truncated to 123 when the component updates.

Metadata

Metadata

Assignees

No one assigned

    Labels

    need guidanceThe approach/solution in the PR is unclear and requires guidance from maintainer to proceed further.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions