'Bootstrap validation in a dual-purpose form not working
I have a form that is used for both Adding and Editing an Organisation. If the form is in Add mode (default) then you also create a default Admin user as part of setting up the Organisation. If the form is in Edit mode (it's passed an organisationId) then you don't see any of the user-related fields.
Validation on the form is working perfectly in Add mode. However in Edit mode I'm finding that it never seems to set the validation to true. I've searched for a solution, but I can't find anything that seems to suit my situation. Hopefully someone here has some insights.
The site is a React app, and I'm using react-bootstrap in case that makes a difference.
Here is the form code:
<Form noValidate={true} validated={validated} onSubmit={handleSubmit}>
<FloatingLabel controlId="name" label="Organisation Name" className="mb-3">
<Form.Control
type="text"
onChange={(e) => setName(e.target.value)}
value={name}
required
placeholder="Organisation Name"
/>
</FloatingLabel>
{!id?.length && (
<fieldset name="Create Admin User" className="border p-2 mb-3">
<legend className="w-auto">Create Admin User</legend>
<FloatingLabel controlId="email" label="Email" className="mb-3">
<Form.Control
type="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
required
placeholder="Email"
/>
</FloatingLabel>
<FloatingLabel controlId="username" label="Username" className="mb-3">
<Form.Control
type="text"
autoComplete="off"
onChange={(e) => setUser(e.target.value)}
value={user}
required
placeholder="Username"
/>
<Form.Control.Feedback type="invalid">
4 to 24 characters.
<br />
Must begin with a letter.
<br />
Letters, numbers, underscores, hyphens allowed.
</Form.Control.Feedback>
</FloatingLabel>
</fieldset>
)}
<Button type="submit">Save Organisation</Button>
</Form>
And here is the submit handler (with the actual form processing cut out, because it's not relevant here - it either works, or we never get to it!):
const handleSubmit = async (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
if (id?.length) {
// EDIT MODE
if (validated) {
alert('EDITING');
// The actual form processing should happen here, but that alert never pops up
}
} else {
// NEW ORG MODE
if (validated) {
// We actually get into this if-statement and can process the form as expected
}
}
};
Has anyone run into this sort of issue before? Am I right in my understanding that the non-displayed fields in Edit mode are causing the problem, or is there something else going on here?
Solution 1:[1]
I copy pasted your code snippets and it works on my side - I see alert with "EDITING":
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Igor Gonak |