← Back to patterns
Multiple submit buttons
One form, two actions, picked by the button that was clicked
Pattern Usage:
export const loginOrRegister = form(
z.object({
email: z.email(),
_password: z.string().min(8),
action: z.enum(['login', 'register'])
}),
async ({ email, _password, action }) => {
if (action === 'login') { ... } else { ... }
}
);
<button {...loginOrRegister.fields.action.as('submit', 'login')}>
Log in
</button>
<button {...loginOrRegister.fields.action.as('submit', 'register')}>
Register
</button> Live Demo:
How it works: Add the action as a field to the schema and spread .as('submit', value) onto each button. The clicked button's
value is submitted with the form, so the handler can branch on it, and the schema makes sure only
known actions get through.
This works without JavaScript too. The password field is named _password, so after a failed no-JS submission it is
not written back into the HTML.