This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
/
useCompanyValidator.ts
64 lines (57 loc) · 1.64 KB
/
useCompanyValidator.ts
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
62
63
64
// Copyright (c) 2022. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
import { useCallback, useEffect, useState } from "react";
import { VoidCallback } from "../../core/interfaces/callbacks";
import { trim } from "../../core/functions/trim";
/**
* @param name
* @param businessId
* @param required
*/
export function useCompanyValidator (
name: string | undefined,
businessId : string | undefined,
required: boolean = true
) : [boolean, VoidCallback] {
const validateCallback = useCallback(
(
isRequired: boolean,
name: string | undefined,
businessId: string | undefined
) => {
const nameString = trim(name ?? '');
const businessIdString = trim(businessId ?? '');
if (isRequired) {
return !!nameString && !!businessIdString;
} else {
return (!nameString && !businessIdString) ? true : (!!nameString && !!businessIdString);
}
},
[
]
);
const [isValid, setValid] = useState<boolean>( validateCallback(required, name, businessId) );
const revalidateCallback = useCallback(
() => {
setValid( () => validateCallback(required, name, businessId));
},
[
setValid,
validateCallback,
required,
name,
businessId
]
);
useEffect(
() => {
revalidateCallback();
},
[
revalidateCallback,
required,
name,
businessId
]
);
return [isValid, revalidateCallback];
}