const formValidation = function (fields) {
    let valid = true;
    for (let i = 0; i < fields.length; i++) {
        fields[i].closest('.form-element').classList.remove('form-element-error');
        fields[i].closest('.form-element').classList.remove('form-element-success');
        fields[i].closest('.form-element').classList.remove('form-element-error-email');

        if (fields[i].value === '' && fields[i].hasAttribute('required')) {
            fields[i].closest('.form-element').classList.add('form-element-error');
            fields[i].closest('.form-element').classList.remove('form-element-error-email');
            valid = false;
        } else if (fields[i].type === 'email' && fields[i].value !== '') {
            fields[i].parentElement.classList.remove('form-element-error');
            if (String(fields[i].value)
                .toLowerCase()
                .match(
                    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                ) === null) {
                fields[i].parentElement.classList.add('form-element-error', 'form-element-error-email');
                valid = false;
            } else {
                fields[i].parentElement.classList.remove('form-element-error', 'form-element-error-email');
                fields[i].parentElement.classList.add('form-element-valid');
            }
        }
    }
    return valid;
}

export {formValidation}