Skip to content
GitHub

Form validation

Kameo uses the Constraint Validation API with support for custom validator functions that extend native validation through setCustomValidity method. If you use required fields or inputs with a specific type in your form, they will be validated automatically.

Validation only works for fields that are form-associated custom elements.

const kameo = new Kameo({
  element: document.querySelector('#kameo'),
  extensions: [
    StarterKit,
    FormKit,
  ],
  content: json,
  documentMode: 'view',
});

kameo.on('submit', (event) => {
  // Check that the form is valid
  if (!event.valid) {
    event.setResult({
      success: false,
      message: 'Form is not valid',
    });
    return;
  }

  // Get form data without nodes
  const formData = Object.fromEntries(
    Object.entries(event.formData).map(([_key, data]) => [data.name, data.value])
  );

  event.setResult({
    success: true,
    message: 'Form is submitted',
  });
});

kameo.on('submit:result', (event) => {
  if (!event.success) {
    return;
  }
});

You can provide customValidator function that will be called for each form-associated field.

const kameo = new Kameo({
  element: document.querySelector('#kameo'),
  extensions: [
    StarterKit,
    FormKit,
  ],
  content: json,
  documentMode: 'view',
  validationOptions: {
    customValidator: ({ node, element }) => {
      if (node.type.name === 'formInput') {
        if (node.attrs.name === 'name' && !node.attrs.value) {
          return 'Please provide a name';
        }
        if (node.attrs.name === 'email' && !node.attrs.value) {
          return 'Please provide an email';
        }
      }
      return '';
    },
  },
});

To validate a form programmatically use kameo.validate() method.

kameo.validate(options);