Skip to main content

Form Validation On Submit New

This template explains how to validate form fields and show relevant error messages in an accessible manner when the user submits a form. Validation on submit is a good default for most forms, but some situations may benefit from immediate validation while the user is filling the form - see another template for that.

Hint: Press F on your keyboard to view both templates and components in fullscreen and ESC to exit the fullscreen mode. You can also open the template in a new browser window.


Open in new window
<!DOCTYPE html>
<html class="duet-bg-gradient duet-sticky-footer" lang="fi">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>LähiTapiola</title>
<link rel="stylesheet" href="https://cdn.duetds.com/api/fonts/3.0.46/lib/localtapiola.css" integrity="sha384-5JYmtSD7nykpUvSmTW1CHMoBDkBZUpUmG0vuh+NUVtZag3F75Kr7+/JU3J7JV6Wq" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.duetds.com/api/css/4.0.28/lib/duet.min.css" integrity="sha384-wDs2jncW8Cx05wCmC63VPWf+LNs6zl5HoVGzkWKyrvLzkOkoly9PEA6YKluhz/01" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.duetds.com/api/tokens/4.0.46/lib/tokens.custom-properties.css" integrity="sha384-7+5ZzVlpstuRULythk9AjF5A5RTVVm+QM/dzBlKwfAy7IknFG9yq5pMPypcvJHBD" crossorigin="anonymous" />
<script type="module" src="https://cdn.duetds.com/api/components/8.5.0/lib/duet/duet.esm.js" integrity="sha384-eG4qKthuSEwQVkC5ibCytRvztDjTpxz9F1Vww4uQwXheghN2GJwtYpIIZvZJhDpl" crossorigin="anonymous"></script>
<script nomodule src="https://cdn.duetds.com/api/components/8.5.0/lib/duet/duet.js" integrity="sha384-EIBBbDpu70LtskytP53zG/25bD7QBqTBq3DoXpcxeBgLKXFrEtaVbnKiDswCBlYe" crossorigin="anonymous"></script>
</head>
<body>
<duet-header language="fi"></duet-header>
<duet-layout center>
<div slot="main">
<duet-card padding="large">
<duet-spacer breakpoint="x-small" size="medium"></duet-spacer>

<!-- The form has novalidate attribute to prevent browsers' native error messages appearing -->
<form id="example-form" action="#" novalidate>

<duet-heading level="h1" visual-level="h2">Ota yhteyttä</duet-heading>
<duet-paragraph>
Lähetä meille viesti kun haluat antaa palautetta tai pyytää yhteydenottoa.
Jos olet jo asiakkaamme, asiasi hoituu parhaiten, kun kirjaudut verkkopalveluun.
Täytä kaikki kentät, jotta voimme auttaa sinua mahdollisimman hyvin.
</duet-paragraph>
<duet-spacer size="medium"></duet-spacer>

<!--
The name validation pattern uses unicode classes to match all letters (including combining marks), not
just the latin alphabet. This is to allow names with diacritics, such as "Müller". Additionally we need to
allow spaces and some punctuation to match names like "Hélèn O'Neil" and "Matti M. Korhonen-Virtanen"
-->

<duet-input
label="Nimi"
name="name"
placeholder="Matti Meikäläinen"
pattern="^[\p{Letter}\p{Mark} \.\- ']+$"
accessible-live-error="off"
expand
>
</duet-input>
<duet-input
label="Sähköposti"
name="email"
type="email"
placeholder="mail@example.com"
accessible-live-error="off"
expand
>
</duet-input>
<duet-select
label="Kaupunki"
name="city"
placeholder="Valitse"
accessible-live-error="off"
expand
>
</duet-select>
<duet-textarea
name="message"
label="Viesti asiakaspalveluun"
caption="Kuvaile asiaasi mahdollisimman tarkasti, niin voimme auttaa sinua paremmin."
placeholder="Kirjoita tähän"
accessible-live-error="off"
expand
>
</duet-textarea>
<duet-radio-group
label="Yhteydenoton syy"
direction="horizontal"
name="reason"
accessible-live-error="off"
>

<duet-radio label="Palaute" value="one"></duet-radio>
<duet-radio label="Yhteydenottopyyntö" value="two"></duet-radio>
</duet-radio-group>

<duet-spacer size="x-large"></duet-spacer>

<!-- Alert to show if the form was not submitted due to errors -->
<duet-alert variation="danger" style="display: none;" id="submit-error-message">
<div class="visible"></div>
<!-- This is used to announce errors of each field for screen readers -->
<duet-visually-hidden></duet-visually-hidden>
</duet-alert>

<duet-button submit variation="primary">Lähetä viesti</duet-button>
<duet-button>Keskeytä</duet-button>

</form>
</duet-card>
</div>
</duet-layout>
<duet-footer logo-href="#" language="fi"></duet-footer>

<script>
// First select the form
const form = document.querySelector("#example-form")

// Then select the form fields
const formFields = {
name: form.querySelector("duet-input[name=name]"),
email: form.querySelector("duet-input[name=email]"),
city: form.querySelector("duet-select[name=city]"),
message: form.querySelector("duet-textarea"),
reason: form.querySelector("duet-radio-group[name=reason]"),
}

// Set the options for the city selection
formFields.city.items = [
{ label: "Helsinki", value: "1" },
{ label: "Tampere", value: "2" },
{ label: "Vantaa", value: "3" },
{ label: "Espoo", value: "4" }
]

// Select the error message elements
const submitErrorMessage = document.querySelector("#submit-error-message")
const submitErrorVisibleMessage = submitErrorMessage.querySelector(".visible")
const submitErrorHiddenMessage = submitErrorMessage.querySelector("duet-visually-hidden")


// Once the user types something in the name field, remove the error
for (const field in formFields) {
formFields[field].addEventListener("duetChange", function() {
clearSubmitErrorMessage()
formFields[field].error = ""
})
}

const errorMessages = {
missing: "on pakollinen kenttä",
invalid: {
name: "ei voi sisältää numeroita tai erikoismerkkejä",
email: "ei ole oikeassa muodossa",
general: "on virheellinen"
},
notSubmitted: "Lomaketta ei lähetetty, siinä on virheitä."
}

function clearSubmitErrorMessage() {
submitErrorVisibleMessage.textContent = ""
submitErrorHiddenMessage.textContent = ""
submitErrorMessage.style.display = "none"
}

// validate form on submit
// if there are errors, prevent the form from submitting
form.addEventListener("submit", function(event) {
clearSubmitErrorMessage()

const errors = []

for (const field in formFields) {
const input = formFields[field]
const value = input.value
const nativeElement = input.querySelector("input, textarea")

// Check the field is not empty and that it is valid (use the native element's validity object)
if (!value) {
input.error = errorMessages.missing
errors.push(input)
// Set the required attribute only when validation fails - otherwise screen readers will announce the field
// as invalid already when the user tabs to it for the first time
input.required = true
} else if (nativeElement && !nativeElement.validity.valid) {
input.error = errorMessages.invalid[field] || errorMessages.invalid.general
errors.push(input)
}
}


if (errors.length) {
// Display an error the form was not submitted
submitErrorVisibleMessage.textContent = errorMessages.notSubmitted

// Announce errors of each field to screen readers
// As we use this method to announce the errors, we can set the accessibleLiveError attributes to off
submitErrorHiddenMessage.textContent = errors.map(error => `${error.label}${error.error}`).join(", ")

submitErrorMessage.style.display = "block"

// NOTE: with some forms, you may want to focus the first error, but this is usually not a good idea
// as the focusing will interrupt the screan readers reading out of the errors.
// If you want to focus the first error, you can use the following code:
// if (errors[0].setFocus) {
// // If the field has a setFocus method, use it
// errors[0].setFocus()
// } else {
// // If the field is a radio or choice, focus the first option
// errors[0].querySelector("duet-radio, duet-choice")?.setFocus()
// }

// Prevent the form from submitting
event.preventDefault()
event.stopPropagation()
}
})


// Show data in the footer component (not part of the form validation)
const footer = document.querySelector("duet-footer")
footer.items = [
{ label: 'Hae korvausta', href: '#', icon: 'navigation-make-claim' },
{ label: 'Osta vakuutus', href: '#', icon: 'action-buy-insurance' },
{ label: 'Yhteystiedot', href: '#', icon: 'form-tel' }
]
footer.menu = [
{ label: 'Turvallisuus ja käyttöehdot', href: '#' },
{ label: 'Evästeet', href: '#' },
{ label: 'Henkilötietojen käsittely', href: '#' },
]

</script>
</body>
</html>

Integration

To install this template’s dependencies into your project, run:

npm install @duetds/components
npm install @duetds/css
npm install @duetds/fonts

For further guidelines, please see each package’s documentation.



Tutorials

Follow these practical tutorials to learn how to build simple page layouts using Duet’s CSS Framework, Web Components and other features:

Tutorials

Building Layouts

Tutorials

Using CLI Tools

Tutorials

Creating Custom Patterns

Tutorials

Server Side Rendering

Tutorials

Sharing Prototypes

Tutorials

Usage With Markdown


Troubleshooting

If you experience any issues while using a template, please head over to the Support page for more guidelines and help.