How to use html5 form.checkValidity() with form of custom components in vuejs 2?
With html5 inputs, form validation works well:
<form name="myform" ref="formref">
<input type="text" required />
<button type="submit" @click="submitForm">Ok</button>
</form>
...
methods: {
submitForm() {
if (this.$refs.formref.checkValidity()) sendData();
else showError();
}
}
But if I use custom components, that won't work:
<form name="myform" ref="formref">
<MyCustomInputComponent :required="true" />
<button type="submit" @click="submitForm">Ok</button>
</form>
checkValidity() of the form will always return true.
The question, is how should I implement MyCustomInputComponent to let it works with HTML5 forms validation?
I see two options:
Trying to validate the custom field inside the component. For this I would use @keyup event to fire the validation before submition. If you are using vuetify (it is a very common library) you can use the rules tag to do it.
Use an external library called veeValidate for this.