jQueryではなくReact-BootstrapHTMLフォーム検証を使用する人がいる場合。
これは明示的には使用しませんpattern
が、同じように機能します。
ドキュメントからいくつかの変更を加えているだけです。
function FormExample() {
const [validated, setValidated] = useState(false);
const [textArea, setTextArea] = useState('');
const textAreaRef = useRef(null);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
const isValid = () => {
// Put whichever logic or regex check to determine if it's valid
return true;
};
useEffect(() => {
textAreaRef.current.setCustomValidity(isValid() ? '' : 'Invalid');
// Shows the error message if it's invalid, remove this if you don't want to show
textAreaRef.current.reportValidity();
}, [textArea];
return (
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Row>
<Form.Group md="4" controlId="validationCustom01">
<Form.Label>Text area</Form.Label>
<Form.Control
required
as="textarea"
ref={textAreaRef}
placeholder="Text area"
value={textArea}
onChange={(e) => setTextArea(e.target.value)}
/>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Form.Group>
</Form.Row>
<Button type="submit">Submit form</Button>
</Form>
);
}
render(<FormExample />);