-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform_validation_controller.js
More file actions
34 lines (29 loc) · 933 Bytes
/
form_validation_controller.js
File metadata and controls
34 lines (29 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Controller } from "@hotwired/stimulus"
const debounce = require("lodash.debounce");
// Connects to data-controller="form-validation"
export default class extends Controller {
connect() {
}
static targets = ["form", "output"];
static values = { url: String };
initialize() {
// use debounce so backend validations are called when a user stops typing
this.handleChange = debounce(this.handleChange, 500).bind(this);
}
handleChange(event) {
const formData = new FormData(this.formTarget)
// call the backend form validation endpoint
fetch(this.urlValue, {
method: "POST",
headers: {
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: formData
})
.then(response => response.text())
.then((html) => {
// update the page with errors html
this.outputTarget.innerHTML = html;
})
}
}