HTML5 form validators with Stimulus?


#1

I was wondering if there is a way to use the HTML5 form validators along with stimulus.

For example, I have a form:

<form class="form-custom" action="contact/" method="POST" data-controller="contact-form">
  <input type="text" name="first_name" data-target="contact-form.name" required />
  <input type="submit" data-action="click->contact-form#submit" value="Submit" />
</form>

and a controller:

import { Controller } from 'stimulus';

export default class extends Controller {
  static targets = ["name"]

  submit(event) {
    event.preventDefault(); // Do not submit form

    const name = this.nameTarget.value;

    console.log(`Hello ${name}`);
  }
}

I imagine that the event.preventDefault() is not allowing the html5 form validation, but is there a better way to do this using stimulus?

Thanks!


#2

I haven’t checked, but can you manually check for validity and prevent default afterwards?

submit(event) {
  if (!event.currentTarget.checkValidity()) {
    event.preventDefault(); // Do not submit form
  } else {
    // submit form?
  } 

  const name = this.nameTarget.value;

  console.log(`Hello ${name}`);
  }

#3

Thank you. I was able to resolve it with this code:

submit(event) {
  if (!this.element.checkValidity()) { return; }

  const name = this.nameTarget.value;

  console.log(`Hello ${name}`);
}