I have a problem I can't figure out the solution 🤔 Would like to hear your ideas about this problem.
I created reusable Form and InputField components. The InputField component getting validation prop, a function that returns true or error message whether the input is valid or not
// InputField.vue
const validate = () => {
isValid.value = props.validation(inputValue.value);
};
// App.vue
<InputField
v-model="formData.firstName"
element="input"
required
name="First Name"
:validation="(val) => /^.{2,}$/.test(val) || 'Minimum 2 characters'"
/>
Now in the Form.vue, I have a variable called isValid, and if it's false, the submit function should not work.
So the problem is: How do I check the states of all the InputFields within the Form component(it receives them as a slot) to understand if isValid = true for input, (then to check if all of them are true, which is simple)
Now I'm looking for an efficient way to do that, and to make sure that it will work for multiple forms and inputs if I have it in a different place in the app, I'm not looking for a quick hack
Here is the link to the application: https://codesandbox.io/s/muddy-sun-0ti9m You can take a look to understand exactly what I'm talking about :)
I will recap: The main goal is to check if all inputs are valid by the validation function that had passed to them, and if the Form is not valid it will not be able to submit.
Thanks all!
I´ve did some changes to your provided code, you can watch the changes in this codesandbox. What I did was to let your InputFields to emit something like a unique id, First Names unique id is like firstname in my example, and also their status of validation. The function is called checkValidation and the emit is addded to their implementation with @check-validation="checkValidation".
There is a new object, which handles multiple status of validation. You can create it dynamically in the future, if you want to make this attemp generic. The object is:
const formValidationObject = reactive({
firstname: false,
lastname: false
});
The checkValidation looks like this:
const checkValidation = (object) => {
formValidationObject[object.data.id] = object.data.valid === true;
};
It´s a simple thing. The object passed with the emit contains the id, like "firstname", and the status of validation. The formValidationObject with it´s key will be true if object.data.valid is true, if not, it´s false.
Now you could do something like passing this as a prop to your Form.vue and handle, if anything isn´t validated.