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!
I haven’t checked, but can you manually check for validity and prevent default afterwards?
The creation of web forms has always been a complex task. While marking up the form itself is easy, checking whether each field has a valid and coherent value is more difficult, and informing the user about the problem may become a headache. HTML5...
The HTMLSelectElement.checkValidity() method checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
submit(event) {
if (!event.currentTarget.checkValidity()) {
event.preventDefault(); // Do not submit form
} else {
// submit form?
}
const name = this.nameTarget.value;
console.log(`Hello ${name}`);
}
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}`);
}
1 Like