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

              
                <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Intro to Form Validtion</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <main class="container main">

    <div id="form-submitted-msg">Form successfully submitted!</div>

    <form id="exampleForm" novalidate>
      <div class="input-group">
        <label for="firstName" class="form-label">First name </label>
        <input type="text" id="firstName" name="firstName" class="form-control" required>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="input-group">
        <label for="lastName" class="form-label">Last name </label>
        <input type="text" id="lastName" name="lastName" class="form-control" required>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="input-group">
        <label for="email" class="form-label">Email </label>
        <input type="email" id="email" name="email" class="form-control" required>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="input-group">
        <label for="password" class="form-label">Password </label>
        <input type="password" id="password" name="password" class="form-control" required>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="input-group select">
        <label for="password" class="form-label">Select Account Type </label>
        <select id="accountType" name="accountType" class="form-select" required>
          <option value="Please select an option" selected class="text-muted">Please select an option</option>
          <option value="Free Account">Free Account</option>
          <option value="Premium Account">Premium Account</option>
        </select>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="input-group radio">
        <div class="form-check">
          <input type="radio" id="personal" name="purpose" value="Personal" class="form-check-input" required>
          <label for="personal" class="form-check-label">Personal</label>
          <small class="error-msg invalid-feedback">Required</small>
        </div>
    
        <div class="form-check">
          <input type="radio" id="business" name="purpose" value="Business" class="form-check-input" required>
          <label for="business" class="form-check-label">Business</label>
          <small class="error-msg invalid-feedback">Required</small>
        </div>
      </div>
      <div class="input-group checkbox form-check">
        <input type="checkbox" name="subscribe" id="subscribeYes" class="form-check-input" required>
        <label for="subscribeYes" class="form-check-label">Subscribe to our newsletter?</label>
        <small class="error-msg invalid-feedback">Required</small>
      </div>
      <div class="form-btns">
        <button type="submit" class="btn btn-primary submit" disabled>SUBMIT</button>
        <button type="reset" class="btn btn-secondary">CLEAR FORM</button>
      </div>
    </form>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
  <script src="./main.js"></script>
</body>
</html>
              
            
!

CSS

              
                *, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.main {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

#form-submitted-msg {
  margin-bottom: 3rem;
  border-radius: 3px;
  background-color: rgb(67, 161, 67);
  padding: 0.5rem;
  width: 40%;
  text-align: center;
  color: #fff;
  display: none;
}

#exampleForm {
  width: 40%;
}

.input-group {
  margin-bottom: 1.5rem;
}

.input-group:not(.radio):not(.checkbox) {
  gap: 0.25rem;
  flex-direction: column;
}

.input-group:not(.radio):not(.checkbox) input {
  width: 100%;
  border-radius: 0.375rem !important;
}

.input-group.checkbox {
  gap: 1rem;
}

.input-group.radio {
  display: flex;
  gap: 1.5rem;
  width: 100%;
}

.input-group.select select {
  width: 100%;
}

legend {
  font-size: 1rem;
  width: max-content;
}

.form-btns {
  display: flex;
  width: 100%;
  gap: 1rem;
  margin-top: 2.5rem;
}

.form-btns > button {
  padding: 0.3rem 1.5rem;
}

.form-btns > .submit {
  padding-inline: 3rem;
}

.error-msg {
  display: none;
}
              
            
!

JS

              
                // Write your code here
// Get all the necessary DOM elements
const form = document.getElementById('exampleForm')
const submitButton = document.querySelector('.submit')
const successMessage = document.getElementById('form-submitted-msg')

// Store all form elements in an array by spreading the elements property of the form
const formElements = [ ...form.elements ]

// Create function to check if all form elements are valid
const allInputsValid = () => {
  const valid = formElements.every((element) => {
    if (element.nodeName === 'SELECT') {
      return element.value !== 'Please select an option'
    } else {
      return element.checkValidity()
    }
  })


  return valid
}

// Define a function to handle changes to any form element
const handleChange = () => {
  // Use the forEach() function to execute the provided function once for each element in the formElements array
  formElements.forEach((element) => {
    // If the element is invalid and is not a button, a select dropdown, a checkbox, or a radio button, style it with a red border and red text
    if (!element.checkValidity()
          && element.nodeName !== 'BUTTON'
          && element.nodeName !== 'SELECT'  
          && element.type !== 'checkbox'
          && element.type !== 'radio'
    ) {
      element.style.borderColor = 'red'
      element.nextElementSibling.style.color = 'red'
      element.nextElementSibling.style.display = 'block'
      element.previousElementSibling.style.color = 'red'
    }

    // If the element is valid, reset its style to the original colors
    // The conditions are the same as above for excluding certain elements
    if (element.checkValidity()
          && element.nodeName !== 'BUTTON'
          && element.nodeName !== 'SELECT'
          && element.type !== 'checkbox'
          && element.type !== 'radio'
    ) {
      element.style.borderColor = '#CED4DA'
      element.nextElementSibling.style.color = '#CED4DA'
      element.nextElementSibling.style.display = 'none'
      element.previousElementSibling.style.color = '#212529'
    }

    // If the element is a checkbox or a radio button and is invalid, style it with a red border and red text
    if (!element.checkValidity()
          && (element.type === 'checkbox'
              || element.type === 'radio')
    ) {
      element.style.borderColor = 'red'
      element.nextElementSibling.style.color = 'red'
    }

    // If the checkbox or radio button is valid, reset its style to the original colors
    if (element.checkValidity()
          && (element.type === 'checkbox'
              || element.type === 'radio')
    ) {
      element.style.borderColor = '#CED4DA'
      element.nextElementSibling.style.color = '#212529'
    }

    // If the element is a select dropdown and the default option is selected, style it with a red border and red text
    if (element.nodeName === 'SELECT'
          && element.value === 'Please select an option'
    ) {
      element.style.borderColor = 'red'
      element.nextElementSibling.style.color = 'red'
      element.nextElementSibling.style.display = 'block'
      element.previousElementSibling.style.color = 'red'
    }

    // If an option other than the default is selected in the dropdown, reset its style to the original colors
    if (element.nodeName === 'SELECT'
          && element.value !== 'Please select an option'
    ) {
      element.style.borderColor = '#CED4DA'
      element.nextElementSibling.style.color = '#CED4DA'
      element.nextElementSibling.style.display = 'none'
      element.previousElementSibling.style.color = '#212529'
    }
  })

  // If all form elements are valid, enable the submit button; otherwise, disable it
  if (allInputsValid()) {
    submitButton.removeAttribute('disabled', '')
  } else {
    submitButton.setAttribute('disabled', '')
  }
}

// Define a function to handle form submission
const handleSubmit = (e) => {
  // Prevent the default form submission behavior
  e.preventDefault()

  // If all form elements are valid after the form submission, display a success message, reset the form, and disable the submit button
  if (allInputsValid()) {
    successMessage.style.display = 'block'
    form.reset()
    submitButton.setAttribute('disabled', '')

    // Hide the success message after 3 seconds
    setTimeout(() => {
      successMessage.style.display = 'none'
    }, 3000)
  }
}

// Add event listener to each form element
formElements.forEach((element) => {
  element.addEventListener('change', handleChange)
})

// Add submit listener to the form
form.addEventListener('submit', (e) => handleSubmit(e))
              
            
!
999px

Console