-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix the validation error when page is reload
- Loading branch information
Showing
2 changed files
with
34 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { useEffect, useRef } from 'preact/hooks'; | ||
|
||
import type { TValidator } from '../util/validator'; | ||
|
||
export const useValidator = (validator: TValidator) => { | ||
const ref = useRef<HTMLInputElement>(null); | ||
|
||
useEffect(() => { | ||
const node = ref.current; | ||
|
||
if (node) { | ||
const listener = () => { | ||
const value = node.value.trim(); | ||
|
||
if (node.value !== value) { | ||
node.value = value; | ||
} | ||
|
||
node.setCustomValidity(validator(value) ? '' : 'error'); | ||
}; | ||
|
||
node.addEventListener('input', listener); | ||
listener(); | ||
} | ||
}, []); | ||
|
||
return ref; | ||
}; |