forked from WordPress/gutenberg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.ts
More file actions
61 lines (54 loc) · 1.57 KB
/
validation.ts
File metadata and controls
61 lines (54 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Internal dependencies
*/
import { normalizeFields } from './normalize-fields';
import type { Field, Form } from './types';
/**
* Whether or not the given item's value is valid according to the fields and form config.
*
* @param item The item to validate.
* @param fields Fields config.
* @param form Form config.
*
* @return A boolean indicating if the item is valid (true) or not (false).
*/
export function isItemValid< Item >(
item: Item,
fields: Field< Item >[],
form: Form
): boolean {
const _fields = normalizeFields(
fields.filter( ( { id } ) => !! form.fields?.includes( id ) )
);
const isEmptyNullOrUndefined = ( value: any ) =>
[ undefined, '', null ].includes( value );
return _fields.every( ( field ) => {
const value = field.getValue( { item } );
if ( field.isValid.required ) {
if (
( field.type === 'text' && isEmptyNullOrUndefined( value ) ) ||
( field.type === 'email' && isEmptyNullOrUndefined( value ) ) ||
( field.type === 'url' && isEmptyNullOrUndefined( value ) ) ||
( field.type === 'telephone' &&
isEmptyNullOrUndefined( value ) ) ||
( field.type === 'password' &&
isEmptyNullOrUndefined( value ) ) ||
( field.type === 'integer' &&
isEmptyNullOrUndefined( value ) ) ||
( field.type === undefined && isEmptyNullOrUndefined( value ) )
) {
return false;
}
if ( field.type === 'boolean' && value !== true ) {
return false;
}
}
if (
typeof field.isValid.custom === 'function' &&
field.isValid.custom( item, field ) !== null
) {
return false;
}
return true;
} );
}