Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- 
Demo for blogpost: A Guide To Accessible Form Validation
https://www.smashingmagazine.com/2023/02/guide-accessible-form-validation/
-->

<div class="g-card">
  <h1 class="g-cardTitle">Field validated on submit</h1>
  <div class="demo-side">
    <form class="jsForm" novalidate>
      <div class="field">
        <label for="email" class="field-label">Email</label>
        <input id="email" type="email" class="field-input jsFieldEmail" aria-describedby="emailError" autocomplete="off" />
        <span class="field-hint">
          <span class="field-error" id="emailError" aria-live="assertive">
            <!-- js -->
          </span>

        </span>
      </div>

      <div class="field">
        <label for="phone" class="field-label">Phone number</label>
        <input id="phone" type="phone" class="field-input jsFieldPhone" aria-required="true" aria-describedby="phoneError phoneHint" autocomplete="off" />

        <span class="field-hint">
          <span class="field-error" id="phoneError" aria-live="assertive">
            <!-- js -->
          </span>
          <span id="phoneHint"> For demo purposes, must start with 9.</span>
        </span>
      </div>

      <div class="form-feedback">
        <p class="form-feedback-sr sr-only" aria-live="assertive">
          <!-- js -->
        </p>
        <p class="form-feedback-msg" aria-hidden="true"></p>
      </div>

      <button type="submit" class="btnMain">Save</button>
    </form>

  </div>
</div>

<!-- -->
<!-- -->
<!-- -->

<footer class="g-footer" hidden>
  <p>Made without coffee by <a href="https://twitter.com/a_sandrina_p" class="u-link">Sandrina Pereira</a>.</p>
</footer>
              
            
!

CSS

              
                .field {
  margin-bottom: 16px;

  &.isInvalid {
    color: var(--theme-error);
  }
}

.field-label {
  display: block;
  line-height: 1;
  margin-bottom: 4px;
}

.field-input {
  max-width: 15rem;
  min-height: 3rem;
  border: none;
  border: 1px solid var(--theme-text_1);
  border-radius: 4px;
  font-size: 1.8rem;

  &:focus:not(:focus-visible) {
    outline: none;
  }

  &:focus-visible {
    outline: none;
    box-shadow: var(--theme-focus-shadow);
  }
}

.field-hint {
  display: block;
  font-size: 1.4rem;
  margin-top: 4px;
  color: var(--theme-text_1);
}

.field-error {
  color: var(--theme-error);
}

.form-feedback-msg {
  &.isInvalid {
    border-left: 4px solid var(--theme-error);
    margin-bottom: 16px;
    background-color: #fbe9e9;
    border-radius: 0 4px 4px 0;
    padding: 4px 6px;
  }

  &.isSuccess {
    border-left: 4px solid #10b042;
    margin-bottom: 16px;
    background-color: #e8fdee;
    border-radius: 0 4px 4px 0;
    padding: 4px 6px;
  }
}

.btnMain {
  --btnTxt: var(--theme-bg_0);
  position: relative;
  display: inline-block;
  cursor: pointer;
  min-height: 34px;
  padding: 8px 20px;
  background-color: var(--theme-primary);
  border-radius: 4px;
  border: none;
  color: var(--btnTxt);
  text-align: center;
  transition: color 250ms;

  &:focus {
    outline: none;
    box-shadow: var(--theme-focus-shadow);
  }
}

.vo-quote {
  border-left: 4px solid var(--theme-text_1);
  padding-left: 4px;
  background: #eee;
  border-radius: 0 3px 3px 0;
  margin-top: 12px;
}

// ----- Theme styles ----- //

html {
  font-size: 62.5%;
  --theme-width: 450px;
  --theme-text_0: hsl(0deg 0% 20%);
  --theme-text_1: hsl(0deg 0% 43%);
  --theme-bg_0: hsl(27deg 39% 95%);
  --theme-bg_1: hsl(0deg 0% 100%);
  --theme-primary: hsl(266deg 100% 61%);
  --theme-primary_smooth: hsl(266deg 100% 92%);
  --theme-secondary: hsl(27deg 100% 56%);
  --theme-error: #d52424;
  --theme-focus-shadow: var(--theme-bg_0) 0 0 0 2px,
    var(--theme-secondary) 0 0 0 4px;
}

body {
  background-color: var(--theme-bg_0);
  color: var(--theme-text_0);
  font-family: "IBM Plex Sans", sans-serif;
  font-size: 1.6rem;
  font-weight: 300;
  box-sizing: border-box;
  color: #343434;
  line-height: 1.5;
  padding: 45px 16px 90px; /* for fixed footer */
}

* {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

body * {
  box-sizing: inherit;
}

p {
  margin: 0;
}

// Global components / Utils
.g-hero {
  text-align: center;
  margin-bottom: 32px;
  margin-bottom: 40px;

  h1 {
    font-size: 2.1rem;
    margin: 0;
  }

  p {
    color: var(--theme-text_1);
    font-size: 1.4rem;
  }
}

.g-card {
  position: relative;
  max-width: var(--theme-width);
  padding: 24px 16px;
  margin: 24px auto 60px;
  border: 1px solid var(--theme-primary);
  border-radius: 4px;
  background-color: var(--theme-bg_1);
  box-shadow: 2px 2px var(--theme-primary_smooth);
  min-height: 100px;
}

.g-cardTitle {
  position: absolute;
  top: -30px;
  left: 0;
  // text-transform: uppercase;
  font-size: 1.6rem;
  margin: 0;
  font-weight: 600;
}

.g-footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 24px 16px;
  font-size: 1.4rem;
  text-align: center;
  background: var(--theme-bg_1);
}

.u-link {
  --linkClr: var(--theme-primary);
  position: relative;
  text-decoration: underline;
  -webkit-text-decoration-color: var(--linkClr);
  text-decoration-color: var(--linkClr);
  color: inherit;
  z-index: 0;
  white-space: nowrap;

  &::before {
    content: "";
    position: absolute;
    bottom: 0.05em;
    left: -0.1em;
    width: calc(100% + 0.2em);
    height: 1.2em;
    background-color: var(--linkClr);
    border-radius: 3px;
    opacity: 0.2;
    transform: scale(1, 0.2);
    transform-origin: 0 95%;
    z-index: -1;
    transition: transform 175ms ease-out;
  }

  &:hover::before,
  &:focus::before {
    transition-duration: 350ms ease-in-out;
    transform: scale(1, 1);
  }

  &:focus {
    outline: none;
  }
}

.u-link:hover {
  outline: none;
}

/* screen reader only */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

              
            
!

JS

              
                const emailRegex = /\S+@\S+\.\S+/; // has @ and .
const phoneRegex = /^9+/; // starts with 9

const elForm = document.getElementsByClassName("jsForm")[0];
const elEmail = document.getElementsByClassName("jsFieldEmail")[0];
const elPhone = document.getElementsByClassName("jsFieldPhone")[0];

const formErrors = {
  email: false,
  phone: false
};

let hasSubmitted = false;

validateField({
  elField: elEmail,
  validateFn: validateFieldEmail
});

validateField({
  elField: elPhone,
  validateFn: validateFieldPhone
});

function validateField({ elField, validateFn }) {
  let touched = false;

  elField.addEventListener("change", (e) => {
    touched = true; // mark it as touched so that on blur it shows the error.
  });

  elField.addEventListener("keyup", (e) => {
    // remove any error on keyup if existent
    validateFn(e.target, { removeOnly: true });

    if (hasSubmitted) {
      updateSubmitSummary();
    }
  });

  elField.addEventListener("blur", (e) => {
    if (!touched) return;
    // show error if touched
    validateFn(e.target, { live: true });
  });
}

function validateFieldEmail(el, opts) {
  const isEmail = emailRegex.test(el.value);
  const isEmpty = el.value === "";
  const isValid = isEmpty || isEmail;

  updateFieldDOM(el, isValid, "Invalid email.", opts);
  formErrors.email = !isValid;
}

function validateFieldPhone(el, opts) {
  const isEmpty = el.value === "";
  updateFieldDOM(el, !isEmpty, "Phone required.", opts);

  if (isEmpty) {
    formErrors.phone = true;
  } else {
    const isPhoneValid = el.value.match(phoneRegex);
    console.log("isPhoneValid", isPhoneValid);
    updateFieldDOM(el, isPhoneValid, "Invalid phone.", opts);
    formErrors.phone = !isPhoneValid;
  }
}

function updateFieldDOM(el, isValid, errorMessage, opts) {
  const removeOnly = opts?.removeOnly;
  const isLive = opts?.live;
  const elField = el.closest(".field");
  const elError = elField.querySelector(".field-error");

  if (isValid) {
    elField.classList.remove("isInvalid");
    elError.innerText = ""; // It's valid
    el.removeAttribute("aria-invalid");
  } else if (!removeOnly) {
    elField.classList.add("isInvalid");
    el.setAttribute("aria-invalid", "true");
    elError.setAttribute("aria-live", isLive ? "assertive" : "off");
    elError.innerText = errorMessage;
  }
}

function updateSubmitSummary({ isSubmit } = {}) {
  const elSummary = elForm.querySelector(".form-feedback");
  const elSummaryMsg = elSummary.querySelector(".form-feedback-msg");

  // Clear form feedback
  elSummaryMsg.classList.remove("isInvalid");
  elSummaryMsg.classList.remove("isSuccess");
  elSummaryMsg.innerText = "";
  const errorsState = Object.values(formErrors);

  if (errorsState.includes(true)) {
    // Show error msg
    const errorCount = Object.values(formErrors).reduce((total, hasError) => {
      return hasError ? total + 1 : total;
    }, 0);
    const errorMsg =
      errorCount === 1
        ? `Failed to save because ${errorCount} field is invalid.`
        : `Failed to save because ${errorCount} fields are invalid.`;
    elSummaryMsg.classList.add("isInvalid");
    elSummaryMsg.innerText = errorMsg;

    elSummary.querySelector(".form-feedback-sr").innerText = isSubmit
      ? // Set SR error message only on submit to avoid being re-announced
        // every time the error summary visually changes.
        errorMsg
      : "";
  } else if (isSubmit) {
    const successMsg = "Saved with success.";
    elSummary.querySelector(".form-feedback-sr").innerText = successMsg;
    elSummaryMsg.innerText = successMsg;
    elSummaryMsg.classList.add("isSuccess");
  }
}

elForm.addEventListener("submit", (e) => {
  e.preventDefault();
  hasSubmitted = true;

  // Validate again
  validateFieldEmail(elEmail);
  validateFieldPhone(elPhone);

  updateSubmitSummary({ isSubmit: true });
});

              
            
!
999px

Console