Skip to content
v0.9.1
Forms

Validation

Tell people what is wrong, next to the field, in plain words. Momo checks the form when it is sent, using the rules you already wrote in HTML, and shows the messages in its own style.

A form that checks itself

Add data-momo-validate to the form. Press "Create account" with the fields empty, then fix them: each one turns fine as soon as it is right.

We send the receipt here.

<form data-momo-validate id="vl-form" style="max-width: 26rem">
  <div class="form-field">
    <label class="form-label" for="vl-name">Shop name</label>
    <input class="form-control" id="vl-name" name="shop" required minlength="3" data-error-required="Give your shop a name." data-error-short="Use at least 3 letters.">
  </div>
  <div class="form-field">
    <label class="form-label" for="vl-email">Email</label>
    <input class="form-control" id="vl-email" name="email" type="email" required data-error-required="Enter your email address." data-error-type="That does not look like an email address.">
    <p class="form-hint">We send the receipt here.</p>
  </div>
  <div class="form-field">
    <label class="form-label" for="vl-plan">Plan</label>
    <select class="form-select" id="vl-plan" name="plan" required data-error="Choose a plan.">
      <option value="">Choose one</option><option>Free</option><option>Team</option><option>Business</option>
    </select>
  </div>
  <div class="form-field">
    <label class="form-label" for="vl-pass">Password</label>
    <input class="form-control" id="vl-pass" name="password" type="password" required minlength="8" data-error-required="Choose a password." data-error-short="Use at least 8 characters.">
  </div>
  <div class="form-field">
    <label class="form-label" for="vl-pass2">Password again</label>
    <input class="form-control" id="vl-pass2" name="password2" type="password" required data-match="#vl-pass" data-error-required="Type the password once more." data-error-match="The two passwords are not the same.">
  </div>
  <div class="form-field">
    <label class="check"><input type="checkbox" name="terms" required data-error="Please accept the terms to go on."> I accept the terms</label>
  </div>
  <div class="cluster">
    <button class="btn btn-brand" type="submit">Create account</button>
    <button class="btn btn-ghost" type="reset">Clear</button>
  </div>
</form>
<script>
  document.getElementById('vl-form').addEventListener('submit', function (e) {
    e.preventDefault();   // this only runs when everything is right; your form would really be sent here
    Momo.toast({ title: 'Account created', color: 'green', icon: 'check' });
  });
</script>
<form data-momo-validate>
  <div class="form-field">
    <label class="form-label" for="email">Email</label>
    <input class="form-control" id="email" type="email" required
      data-error-required="Enter your email address."
      data-error-type="That does not look like an email address.">
  </div>
  <button class="btn btn-brand" type="submit">Create account</button>
</form>

How it works

  1. Write the rules in HTML as usual: required, type="email", minlength, maxlength, min, max, pattern.
  2. When the form is sent, every field is checked. If something is wrong the form is not sent, the first wrong field gets the focus, and each one shows its message.
  3. A wrong field is checked again while it is being fixed, so the red goes away at once.
  4. Your own submit handler only runs when everything is right.

Your own words

Without anything, the browser's own message is shown. data-error replaces it for the whole field; the longer names replace it for one rule.

AttributeWhen it is shown
data-errorWhatever is wrong (unless a more exact one below is set)
data-error-requiredThe field is empty, or the box is not ticked
data-error-typeNot an email address, a web address or a number
data-error-short, data-error-longShorter than minlength, longer than maxlength
data-error-min, data-error-maxBelow min, above max
data-error-patternDoes not fit the pattern
data-match="#other", data-error-matchMust be the same as another field (a password typed twice)

Messages as small flags

data-momo-validate="tip" hangs each message under its field as a small flag, so the form does not get taller. Good for tight rows and inline forms.

<form class="form-inline" data-momo-validate="tip" id="vl-tip" style="padding-bottom: 1.75rem">
  <div class="form-field form-field-grow"><label class="form-label" for="vt-mail">Email</label><input class="form-control" id="vt-mail" type="email" required placeholder="you@example.com" data-error="Enter a full email address."></div>
  <div class="form-field"><label class="form-label" for="vt-seats">Seats</label><input class="form-control" id="vt-seats" type="number" min="1" max="50" value="0" required style="width: 6rem" data-error-min="At least 1." data-error-max="At most 50."></div>
  <button class="btn btn-brand" type="submit">Invite</button>
</form>
<script>document.getElementById('vl-tip').addEventListener('submit', function (e) { e.preventDefault(); Momo.toast({ title: 'Invitation sent', color: 'green', icon: 'check' }); });</script>

Errors from your server

Some things only the server knows: the name is taken, the code has expired. Show those with Momo.validate.set(). The message stays until the person changes the field.

Try "momo": it is taken.

<form data-momo-validate id="vl-server" style="max-width: 26rem">
  <div class="form-field">
    <label class="form-label" for="vs-user">Username</label>
    <input class="form-control" id="vs-user" name="user" required value="momo" data-error-required="Choose a username.">
    <p class="form-hint">Try "momo": it is taken.</p>
  </div>
  <button class="btn btn-brand" type="submit">Save</button>
</form>
<script>
  document.getElementById('vl-server').addEventListener('submit', function (e) {
    e.preventDefault();
    var field = document.getElementById('vs-user');
    // a pretend answer from the server
    if (field.value.trim().toLowerCase() === 'momo') Momo.validate.set(field, 'That name is taken. Try momo-goods.');
    else Momo.toast({ title: 'Saved', color: 'green', icon: 'check' });
  });
</script>
const answer = await send(form);
if (answer.errors.user) Momo.validate.set('#user', answer.errors.user);

Without the script

The classes work on their own: .is-invalid or .is-valid on the field with a .form-error or .form-ok message under it, as shown on Fields & labels. Fields also turn red by themselves after someone has typed something wrong (:user-invalid).

Good to know

Reference

Attribute / APIWhat it does
data-momo-validate, ="tip"Check the form when it is sent; show messages as small flags
data-error, data-error-…Your words for a field, or for one rule
data-match="#other"The field must be the same as that one
Momo.validate(form)Check now; true when everything is right
Momo.validate.set(field, message)Show a message from your server; an empty message clears it
Event momo:invalidOn the form when it was not sent; detail: { fields }

Start

OverviewStart Getting startedStart CustomizeStart

Guides

AccessibilityGuides BreakpointsGuides ChangelogGuides Customize componentsGuides JavaScriptGuides MotionGuides OptimizeGuides PhonesGuides RebootGuides Right-to-left (RTL)Guides Stacking orderGuides Using Momo with AIGuides

Foundations

ColorsFoundations TypographyFoundations ProseFoundations Images & figuresFoundations CodeFoundations Lines & shadowsFoundations Dark modeFoundations

Forms

Checkbox & switchForms ComboboxForms Date pickerForms Date rangeForms Fields & labelsForms File uploadForms Floating labelsForms Number stepperForms PasswordForms PIN codeForms RatingForms SelectForms SliderForms Tag inputForms Time pickerForms ValidationForms

Components

AccordionComponents Alert & bannerComponents AvatarComponents BadgeComponents BreadcrumbComponents ButtonComponents Button groupComponents CalendarComponents CardComponents CarouselComponents ChartsComponents ChipsComponents CollapseComponents Command paletteComponents CommentsComponents Confirm dialogsComponents Cookie bannerComponents Data tableComponents Description listComponents Dialog & toastComponents DividerComponents DrawerComponents Dropdown menuComponents Empty stateComponents File managerComponents Filter & sortComponents Gallery & lightboxComponents Inbox & chatComponents Infinite scrollComponents KanbanComponents Keyboard shortcutsComponents List groupComponents MarqueeComponents Media objectComponents Nav overflowComponents Notification centerComponents PaginationComponents ProgressComponents Pull to refreshComponents SkeletonComponents SortableComponents SpinnerComponents Split viewComponents Stat cardComponents Steps & wizardComponents Swipe actionsComponents TableComponents TabsComponents TimelineComponents TogglerComponents Tooltip & popoverComponents TourComponents Tree viewComponents VideoComponents WhiteboardComponents

Layout

Announcement barLayout App shellLayout Back to topLayout Container & sectionLayout ExamplesLayout FooterLayout HeroLayout JumbotronLayout Mega menuLayout NavbarLayout Site sidebarLayout

Sections

Bento gridSections Blog cardsSections Call to actionSections Contact & newsletterSections FAQSections FeaturesSections Logo cloudSections PricingSections TeamSections TestimonialsSections

Utilities

OverviewUtilities State variantsUtilities Display & flexUtilities Grid & gapUtilities SpacingUtilities SizingUtilities TextUtilities Links & color strengthUtilities Position & overflowUtilities BackgroundsUtilities Borders & effectsUtilities Transforms & filtersUtilities InteractionsUtilities

Helpers

Fixed, sticky & frostedHelpers Hover & focusHelpers Hover revealHelpers Icon linkHelpers PrintHelpers Relative timeHelpers Screen reader textHelpers Scroll inHelpers ScrollspyHelpers Share buttonHelpers Skip linkHelpers StacksHelpers Stretched linkHelpers Theme toggleHelpers Truncated textHelpers

Page patterns

404 pagePage patterns Coming soonPage patterns Login & registerPage patterns SettingsPage patterns ProfilePage patterns CRM contactsPage patterns ProjectsPage patterns File manager pagePage patterns Billing & plansPage patterns Help centerPage patterns Mobile app screensPage patterns
↑ ↓ moveEnter openEsc close