I'm currently building a form in Vue js and I'm using Vueformulate, the docs have various ways of validation however there is no validation method or implementation that for my use case. I would like the validation to call a custom function because this way I could check if Field1 or Field2 has a value. Is there an implementation like my psuedocode below? thanks in advance!
<FormulateForm @submit="onSubmit" #default="{ hasErrors }">
<FormulateInput
type="text"
label="Field1"
validation="customValidation"
/>
<FormulateInput
type="text"
label="Field2"
validation="customValidation"
/>
<FormulateInput
type="submit"
label="Submit"
input-
:disabled="hasErrors"
/>
</FormulateForm>
//NOT REAL CODE
customValidation(formValues){
if(formValues.Field1 || formValues.Field2){
return true // CHECK IF EITHER FIELD1 OR FIELD 2 HAS VALUE IF SO MARK THE FIELD AS VALID WHICH ENABLES SUBMIT BUTTON
}
return false
}
CodePudding user response:
You can declare a custom validation rule via <FormulateInput>.validationRules
:
<script setup>
const validationRules = {
customValidation({ getFormValues }) {
// property names match the input names
const { field1, field2 } = getFormValues()
if (field1 || field2) {
return true
}
},
}
</script>
<template>
<FormulateInput
type="text"
label="Field1"
name="field1"
validation="customValidation"
:validationRules="validationRules"
/>
<FormulateInput
type="text"
label="Field2"
name="field2"
validation="customValidation"
:validationRules="validationRules"
/>
</template>
But FormulateForm
assumes an error state unless all fields are touched (at least in my demo). Not sure how you could get around that.