I have a text field to enter a title in a dialog modal. There a button called 'create' that when clicked both adds an item to a table AND closes the dialog modal.
<Button onClick={createProjectButtonHandler} variant="contained">
And the function that handles this is:
const createProjectButtonHandler = () => {
props.onSaveProjectData(projectData);
props.onCloseModal();
setProjectTitle("");
};
Here is my title validation function and state:
// title validation state and handler
const [titleError, setTitleError] = useState(false);
const validateTitle = (title) => {
return title === 0 ? setTitleError(true) : setTitleError(false);
};
Here my input field:
<TextField
label="Title"
variant="outlined"
required
onChange={projectTitleHandler}
error={titleError}
helperText={titleError && "Please enter a title"}
></TextField>
How do I add this validation function to the createProjectButtonHandler function so that these two: props.onSaveProjectData(projectData); props.onCloseModal(); only happen when titleError is false, otherwise when clicking the button and titleError is true I want to show that error.
In short, I want to validate the input text AFTER clicking the button. If no errors, then proceed.
import { useForm} from "react-hook-form";
const { register, handleSubmit, errors} = useForm();
const submitForm = (data) => {
props.onSaveProjectData(data);
props.onCloseModal();
setProjectTitle("");
}
<form onSubmit={handleSubmit(submitForm)}>
<Grid item>
<TextField
name="Title"
label="title"
type={"text" }
ref={register({ required: true })}
error={!!errors.Title}
helperText="Please enter a title"
/>
</Grid>
<Grid item>
<Button type="submit">
submit
</Button>
</Grid>
</form>