Skip to content

Commit 52e288a

Browse files
committed
test: add wildcard test
1 parent 8c57402 commit 52e288a

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/__tests__/validator.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ describe('Validator', () => {
1313
})
1414
test('Add an error', () => {
1515
validator.add('name', 'The name field is required.')
16+
validator.add('name', 'The name field min length is 3.')
1617
expect(validator.any()).toBeTruthy()
1718
})
1819
test('Add an error with forceUpdate', () => {
@@ -240,4 +241,18 @@ describe('Validator', () => {
240241

241242
expect(validator.has(['firstName'])).toBeFalsy()
242243
})
244+
245+
it('should work with wildcard fields', () => {
246+
const errors = {
247+
'items.0.name': ['This fist name field is required'],
248+
'items.1.name': ['This fist name field is required'],
249+
'items.2.name': ['This fist name field is required'],
250+
}
251+
validator.fill(errors)
252+
253+
expect(validator.has(['items.*'])).toBeTruthy()
254+
expect(validator.has(['items.*.name'])).toBeTruthy()
255+
expect(validator.first(['items.*.name'])).toEqual('This fist name field is required')
256+
expect(validator.first(['items.0.name'])).toEqual('This fist name field is required')
257+
})
243258
})

src/core/Validator.ts

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,7 @@ import { castArray, cloneDeep, get, has, omit, replace } from 'lodash'
33
import { is, toCamelCase, toSnakeCase } from '../util'
44

55
class Validator {
6-
public successful: boolean
7-
public processing: boolean
8-
9-
constructor(public errors: SimpleObject<any> = {}) {
10-
this.processing = false
11-
this.successful = false
12-
}
6+
constructor(public errors: SimpleObject<any> = {}, public processing = false, public successful = false) {}
137

148
add(field: string, message: string, forceUpdate?: boolean) {
159
if (forceUpdate || this.missed(field)) {
@@ -24,16 +18,15 @@ class Validator {
2418
return is(Object.keys(this.errors), fields)
2519
}
2620

27-
first(field: string | string[]): string | undefined {
21+
first(field: string | string[]) {
2822
const fields = this.fields(castArray(field))
2923
const foundField = fields.find((f) => has(this.errors, f)) ?? ''
3024
const value = this.get(foundField)
3125
return Array.isArray(value) ? value[0] : value
3226
}
3327

3428
firstBy(obj: SimpleObject<any>, field: string = Object.keys(obj)[0]): string {
35-
const value: string = obj[field]
36-
return Array.isArray(value) ? value[0] : value
29+
return castArray(obj[field])[0]
3730
}
3831

3932
missed(field: string | string[]) {

0 commit comments

Comments
 (0)