brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: formnovalidate on a Save draft button skips the required fields check

Web-Development
~/tips/tip-formnovalidate-save-draft

Save draft

One button submits without validation while the main button still checks everything.

A long form with required fields has a problem: people cannot save a half finished draft, because the browser blocks the submit. A second button with formnovalidate gets around that for that button only.

<form method="post" action="/posts/publish">
  <input name="title" required>
  <textarea name="body" required minlength="200"></textarea>

  <button type="submit">Publish</button>
  <button type="submit" formnovalidate formaction="/posts/draft">
    Save draft
  </button>
</form>

formnovalidate on a submit button means “submit without the browser’s built-in validation”. The Publish button still enforces required and minlength, the draft button does not. formaction sends the draft to another URL, so the server knows which button was used without checking the button’s name.

There are more of these overrides: formmethod, formenctype and formtarget change the method, encoding and target for one button. I like that this needs no JavaScript at all.

The obvious but important caveat: browser validation is a convenience for the visitor, not a security check. Anyone can skip it with this attribute or the developer tools. The server has to validate the publish request on its own, and it must accept incomplete data on the draft route without falling over.

Further reading: MDN: The button element, MDN: Client-side form validation

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { spellcheck="false" All Web-Development tips (67) All topics

Link