Meteor-Community-Packages / meteor-autoform

AutoForm is a Meteor package that adds UI components and helpers to easily create basic forms with automatic insert and update events, and automatic reactive validation.
MIT License
1.44k stars 328 forks source link

Why is there throttling on validateField #1724

Open stefanve opened 1 year ago

stefanve commented 1 year ago

I have a big schema and has splitted the form in parts for easier fill in/overview. That means that I cannot use validateForm, but instead validate each field.

I do (basically) :

Object.keys(AutoForm.getFormValues(formId).insertDoc) => (f){
    if(!(AutoForm.validateField(formId, f))){
          //handle error
        }
}

This works well if I step through it in the debugger, but when run normally, validateField returns true whatever the reality is.

Am I missing some logic here? Why is the throttle there? Is my approach unique and wrong?

From the package code:

// Throttle field validation to occur at most every 300ms,
// with leading and trailing calls.
export const validateField = throttle(_validateField, 300)
jankapunkt commented 1 year ago

The throttle code is necessary, since validation triggers reactivity a lot, especially if you have many reactive fields. We could, however introduce an API, where you set a different throttling speed or disable throttle at all, if that would help you.

If you use simple schema, you could also do manual validation this way:

const { insertDoc } = AutoForm.getFormValues(formId)
const context = formSchema.newContext() // formSchema is the schema you use for this form
context.validate(formDoc, options) // options is optional but can be useful, like clean options

const errors = context.validationErrors()

if (errors && errors.length > 0) {
  errors.forEach(err => AutoForm.addStickyValidationError(formId, err.key, err.type, err.value))
  return // form is invalid
}

// otherwise remove sticky validation errors and continue with insert doc
stefanve commented 1 year ago

Ok, I understand and thanks for the workaround. Maybe it should be mentioned in the docs that validateField cannot be looped though? Time spent...