Validate Programmatically

by brendanbond

HTML

<link
  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
  rel="stylesheet"
  integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB"
  crossorigin="anonymous"
/>
<link rel="stylesheet" href="https://cdn.form.io/js/formio.full.min.css" />

<div class="container">
  <div id="formio"></div>
</div>
<script src="https://cdn.form.io/js/formio.full.js"></script>

CSS

.radio-block label {
  background: #228b22;
  border: 3px solid transparent;
  cursor: pointer;
}
.radio-block.radio-selected label {
  border-color: black;
}

@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
@keyframes slideInFromLeft {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
.wizard-page.slide-left {
  animation: slideInFromRight 0.4s ease-out;
}
.wizard-page.slide-right {
  animation: slideInFromLeft 0.4s ease-out;
}

JavaScript

// Render the form, disable submit and just render the submission in the logs
Formio.createForm(document.getElementById('formio'), {
  components: [
    {
      label: 'First Name',
      key: 'firstName',
      type: 'textfield',
      input: true,
      validate: {
        required: true
      }
    },
    {
      label: 'Last Name',
      key: 'lastName',
      type: 'textfield',
      input: true,
    },
    {
      label: "Check Form",
      key: "checkForm",
      type: "button",
      action: "event",
      event: "checkForm",
    }
  ],
}).then((form) => {
  form.on("checkForm", () => {
    // set "pristine" to false to simulate someone having used the form
    form.setPristine(false);
    // validate 
    form.validate();
    // show the errors
    form.showErrors();
  })
})