HTML Form validation in raw javascript with DOM

Viewed 17

It seems i have broken my working code. The form now submit without file validation, which it should not.

document.addEventListener('DOMContentLoaded', function(){
        function validate(){
        var pTagMsg = document.querySelector('#ptagmsg');                    
        var inpsText = document.querySelectorAll('.textinputs');
        var inpFile = document.querySelector('#upload');
        var regForm = document.querySelector('.regform');
        
        for(let i = 0; i < inpsText.length; i++){
            // check if text input fields are not filled.
            let fieldValue = inpsText[i].value.length;
            if(fieldValue == 0){                
                inpsText[i].focus();
                inpsText[i].style.backgroundColor = 'red';
                return false;
       } else if (fieldValue != 0){
          // if input fields containn values.
          inpsText[i].style.backgroundColor = 'green';
       }
    }
    var fileObjList = inpFile.files;
    var fileObj = inpFile.files[0];
    var fileValue = inpFile.value;
    var fileName = fileObj.name;
    var fileExt = fileObj.name.slice(-4);
    var fileSize = Math.round(fileObj.size / 1024);
    var size = 300; // size in kb.
    if(fileObjList.length === 0){
    pTagMsg.textContent = "Attachment Required";
    pTagMsg.style.backgroundColor = 'red';
    return false;
    } else {
    // check for extension and size.
    if((fileExt == '.pdf') && (fileSize <= size)){
    pTagMsg.textContent =  'file selected, OK!: ' + fileExt +', '+ fileSize;
    pTagMsg.style.backgroundColor = 'green';                        
    } else {
    pTagMsg.textContent = 'file must be: '+ fileExt + 'and size of: ' + size + 'kB !';
    }                       
    }
    }
    // calling the submit event on the form.
    regForm.addEventListener('submit', validate);
    });
Firstname:
Email:
Surname:
Lastname:
ward:
location landmark:
date:
describe


1 Answers

First of all, I hope you can share your code in beautiful format and indentation.

When you submit form and want to do a validation, you should prevent it from its' default action. Then after all checking complete, you could continue submitting the form.


function validate(e){
    e.preventDefault();

    // rest of your code ...

    if(everythingInvalid) {
        alert("Your form invalided");
        return;
    }

    regForm.submit();
}

regForm.addEventListener('submit', validate)

Please see others references:

Related