HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/somerenslust.komma.pro/resources/assets/js/site/formHandler.js
/**
 * Created by Pascal on 23/11/17.
 */

/**
 *
 * @param {string} id - html id of form
 * @param {array} required - list of required field
 * @constructor
 */

function FormHandler(id, required) {

    // Define form object
    this.formObject = document.getElementById(id);

    // Set required fields
    this.requiredFields = required;

    // Set default valid to true
    this.valid = true;

    // Validate form function
    this.validate = function () {

        // Reset valid to true
        this.valid = true;

        // Define this to self
        var self = this;

        var fieldToValidate = self.requiredFields.slice();

        // Get all form elements
        var formElements = this.formObject.querySelectorAll('input, textarea');

        // Loop through the form elements
        var formElementsLength = formElements.length;
        for(var i = 0; i < formElementsLength; i++){
            var el = formElements[i];

            // Remove alert
            el.classList.remove('alert');

            var indexOfValidator = fieldToValidate.indexOf( el.getAttribute('name'));

            // Check if it's in the required fields
            if( indexOfValidator !== -1 ){

                // Temporary store the value (for future checks or so ex. check if mail)
                var value = el.value;

                // Check if value is filled
                if(value === null || value === ''){

                    // Else set alert and set form valid to false
                    el.classList.add('alert');
                    self.valid = false;
                }

                // Remove from fields to validate array
                fieldToValidate.splice(indexOfValidator, 1);

            }
        }

        // Check if all required fields are filled
        if(fieldToValidate.length !== 0) {

            // Else also set form valid to false
            // And log because it should only happen in development
            self.valid = false;
            console.log('Not all required field are filled:');
            console.log(fieldToValidate);

        }

    };

    // Send form
    this.send = function () {
        this.formObject.submit();
    }

}