Garfieldus
Garfieldus

Reputation: 11

Formvalidation.io: event when certain field is valid

I have a beginner's question on Formvalidation.io. Maybe it's not even specific for that library but more related to Javascript in general.

I'd like to disable a validator after a certain field (let's say its name is postcode) has been validated and is valid. However, all my approaches result in either the validator not being disabled or being disabled if any field of my form is valid (not only the specific one).

I use the core.field.valid event and the library's documentation states:

The event parameter presents the field name.

I'm uncertain how that happens.

I tried:

document.addEventListener('DOMContentLoaded', function(e) {
	const fv = FormValidation.formValidation(
		document.getElementById('adminForm'),
		{
			fields: {
				postcode: {
					validators: {
						notEmpty: {
							message: 'Please enter a postcode.'
						}
					}
				}
			},

			plugins: {			
 				submitButton: new FormValidation.plugins.SubmitButton(),
				defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
				trigger: new FormValidation.plugins.Trigger({
					event: {
						postcode: 'change',
					}
				})
			}
		}
    );

	fv.on('core.field.valid', function(e) {
		if (e.field === 'postcode') {
			fv.disableValidator('postcode');
		}
	});	
});

But the if-condition is not true even when the field is validated and valid. (tried to adapt it from the example given here)

I also tried what I found in the documentation on the on() method (as it states regarding function(field): "field is name of invalid field"):

const validFieldHandler = function(postcode) {
    fv.disableValidator('postcode');
};

fv.on('core.field.valid', validFieldHandler);
Result is the same (validator is not disabled).

The following however (as probably to expect) disables the validator if any field of the form is valid.

fv.on('core.field.valid', function(e) {
    fv.disableValidator('postcode');
});

Thank you for any advice you can offer! It's my first question here, so please let me know if you need additional information!

Best regards, Sebastian

Upvotes: 0

Views: 1645

Answers (1)

Garfieldus
Garfieldus

Reputation: 11

Found the solution myself:

fv.on('core.field.valid', function(field) {
		if (field === 'postcode') {
			fv.disableValidator('postcode');
		}
});

Upvotes: 1

Related Questions