Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions js/formidable.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,12 @@ function frmFrontFormJS() {
maybeAddHttpsToUrl( field );
}
const form = field.closest( 'form' );
if ( form && hasClass( form, 'frm_js_validate' ) ) {
validateField( field );
if ( ! form ) {
return;
}

// Removing stale errors is universal. Adding errors only happens when JS validation is enabled.
validateField( field, hasClass( form, 'frm_js_validate' ) );
}

/**
Expand All @@ -301,11 +304,16 @@ function frmFrontFormJS() {
/**
* Validate a field with JS.
*
* Removing stale errors is universal. Adding errors only happens when JS validation is enabled.
*
* @since x.x Added the `addErrors` parameter.
*
* @param {HTMLElement} field
* @param {boolean} addErrors Whether to add new errors. Defaults to `true`.
*
* @return {void}
*/
function validateField( field ) {
function validateField( field, addErrors = true ) {
let errors;
let key;

Expand All @@ -325,11 +333,18 @@ function frmFrontFormJS() {
validateFieldValue( field, errors, false );
}

removeFieldError( fieldContainer );
if ( Object.keys( errors ).length > 0 ) {
for ( key in errors ) {
addFieldError( fieldContainer, key, errors );
const hasErrors = Object.keys( errors ).length > 0;

if ( addErrors ) {
removeFieldError( fieldContainer );
if ( hasErrors ) {
for ( key in errors ) {
addFieldError( fieldContainer, key, errors );
}
Comment on lines +341 to +343
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrap the body of a for-in loop in an if statement with a hasOwnProperty guard


Looping over objects with a for in loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected keys in your for loop.

}
} else if ( ! hasErrors ) {
// JS validation is off, so only remove existing errors once the field passes validation.
removeFieldError( fieldContainer );
}
}

Expand Down
Loading