vue-generators / vue-form-generator

:clipboard: A schema-based form generator component for Vue.js
MIT License
2.99k stars 531 forks source link

.validate() for a specific field #633

Open ahmed-shahrour opened 5 years ago

ahmed-shahrour commented 5 years ago

Currently, I have two input date fields in my form along with another few. One is startDate and the other is endDate. Logically startDate must be before endDate, and endDate must be after startDate.


These are the custom validators I created for each:

startDate:

const startDateValidation = (value, field, model) => {
  if (value && model.endDate && new Date(value).valueOf() > model.endDate) {
    return ["Start Date must be before End Date."];
  } 
  return [];
};

endDate:

const endDateValidation = (value, field, model) => {
  if (value && model.startDate && new Date(value).valueOf() < model.startDate) {
    return ["End Date must be after Start Date."];
  }
  return [];
};

They are both dependants on each other and I cannot force validate one field without validating the other.


Example: I set (mistakingly) startDate to be: "2019-07-01" then I set endDate to be: "2019-06-01"

If I set options: { validateAfterChanged: true }, then I get a validation red box css happening on the endDate once I selected the date. Now I noticed my mistake I will set startDate to be: "2019-05-01". endDate will continue to be invalid css.

The only clean way I figured out to solve the issue is to attach @model-updated="onModelUpdated" and ref="vfg" to the <VueFormGenerator /> component, then for every change in the model, I force validate the whole form using this.$refs.vfg.validate() in the onModelUpdated method. If there are other fields in the form, then they will be validated as well for any change in startDate or endDate, which I don't want.


asanzdj commented 4 years ago

Hi, To validate only one field you can use validate method declared in abstractField mixin. You can find it here (https://github.com/vue-generators/vue-form-generator/blob/master/src/fields/abstractField.js)

Example:

<script>
        export default {
            name: 'DatePickerField',
            mixins: [abstractField],
            methods: {
                handleDateChange() {
                    [...do your stuff]
                    this.validate(); // This method triggers  this field validation only
                }
            }
        }
</script>
jvgrootveld commented 4 years ago

I had the same issue with 2 separate checkboxes for which it was not allowed to be both checked. I had to implement the quickfix from @ahmadshahrour951.

It would be nice if we could reach other fields from the validator or custom field to manually call validate on a different field.