vue-form-generator icon indicating copy to clipboard operation
vue-form-generator copied to clipboard

.validate() for a specific field

Open ahmed-shahrour opened this issue 6 years ago • 2 comments

  • I'm submitting a ...

    • [ ] bug report
    • [x] feature request
  • What is the current behavior?

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.


  • Suggestion Would it be possible to have a .validate() method for a specific field?

  • Please tell us about your environment:

    • Version: [2.3.4]
    • Browser: [Chrome 75]
    • Language: [ES6/7]

ahmed-shahrour avatar Jul 26 '19 12:07 ahmed-shahrour

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>

asanzdj avatar Oct 31 '19 09:10 asanzdj

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.

jvgrootveld avatar Apr 10 '20 13:04 jvgrootveld