Skip to content

Commit

Permalink
fix: NumberModel should read empty string as undefined (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
haijian-vaadin authored Sep 20, 2021
1 parent 78a3f2b commit 12536a6
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
7 changes: 5 additions & 2 deletions frontend/packages/form/src/Models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export class BooleanModel extends PrimitiveModel<boolean> implements HasFromStri
[_fromString] = Boolean;
}

export class NumberModel extends PrimitiveModel<number> implements HasFromString<number> {
export class NumberModel extends PrimitiveModel<number> implements HasFromString<number | undefined> {
static createEmptyValue = Number;

constructor(
Expand All @@ -105,7 +105,10 @@ export class NumberModel extends PrimitiveModel<number> implements HasFromString
super(parent, key, optional, new IsNumber(optional), ...validators);
}

[_fromString](str: string): number {
[_fromString](str: string): number | undefined {
// Returning undefined is needed to support passing the validation when the value of an optional number field is
// an empty string
if (str === '') return undefined;
return isNumeric(str) ? Number.parseFloat(str) : NaN;
}
}
Expand Down
8 changes: 4 additions & 4 deletions frontend/packages/form/test/Field.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,11 @@ describe('form/Field', () => {
});

it('should update binder value on typing', async () => {
const cases: Array<[string, number]> = [
const cases: Array<[string, number | undefined]> = [
['1', 1],
['1.', NaN], // not allowed format
['1.2', 1.2],
['', NaN],
['', undefined],
['not a number', NaN],
['.', NaN],
['.1', 0.1],
Expand Down Expand Up @@ -421,11 +421,11 @@ describe('form/Field', () => {
});

it('should update binder value on typing', async () => {
const cases: Array<[string, number]> = [
const cases: Array<[string, number | undefined]> = [
['1', 1],
['1.', NaN], // not allowed format
['1.2', 1.2],
['', NaN],
['', undefined],
['not a number', NaN],
['.', NaN],
['.1', 0.1],
Expand Down
4 changes: 2 additions & 2 deletions frontend/packages/form/test/Model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,14 @@ describe('form/Model', () => {
});

describe('_fromString', () => {
let fromString: (str: string) => number;
let fromString: (str: string) => number | undefined;

beforeEach(() => {
fromString = binder.model.fieldNumber[_fromString];
});

it('should disallow empty string', async () => {
expect(fromString('')).to.satisfy(Number.isNaN);
expect(fromString('')).to.equal(undefined);
});

it('should integer format', async () => {
Expand Down

0 comments on commit 12536a6

Please sign in to comment.