2

My form validation isn't working properly and my functions don't stop the page from submitting even when the form fields are empty. I am also only able to hide the errors through css whereas they still show when I comment out the "visibility: hidden;" code to hide them.

**I also get the following errors in console:
Uncaught TypeError: document.getElementById(...) is null:63:13**
    formHasErrors file:///C:/Users/Neal/Desktop/bettaemp/bettascript.js:63
    validate file:///C:/Users/Neal/Desktop/bettaemp/bettascript.js:11
    load file:///C:/Users/Neal/Desktop/bettaemp/bettascript.js:119
    EventListener.handleEvent* file:///C:/Users/Neal/Desktop/bettaemp/bettascript.js:126
bettascript.js

HTML

<form method="post" id="contactus" action="index.html">
                    <fieldset>
                        <legend><h1>Your Contact Info</h1></legend>
                        <div class="formfield" id="form">
                            <label for="firstname" class="customer" >First Name:</label>
                            <input  type="text" id="firstname" name="firstname" placeholder="John" size="30" maxlength="20" autofocus="autofocus" >
                            <div class="customer_error error" id="firstname"> *First name is required*</div>
                        </div>
                        <div class="formfield">
                            <label for="lastname" class="customer">Last Name:</label>
                            <input type="text" id="lastname" name="lastname" placeholder="Doe" size="30"
                            maxlength ="20" >
                            <div class="customer_error error" id="lastname"> *Last name is required*</div>
                        </div>
                        <div class="formfield">
                            <label for="phonenum" class="customer">Phone Number:</label>
                            <input type="tel" id="phonenum" name="phonenum" placeholder="555-555-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" size="30" maxlength ="12" >
                            <div class="customer_error error" id="phonenum"> *Phone number is required e.g 111-111-1111*</div>
                        </div>
                        <div class="formfield">
                            <label for="email" class="customer">Email:</label>
                            <input type="email" id="email" name="email" placeholder="email@email.com" size="30"
                            maxlength ="50" >
                            <div class="customer_error error" id="email_error"> *Last name is required*</div>
                        </div>
                    </fieldset>
                    <fieldset>
                        <div class="formfield">
                            <label for="feedback">What can we help you with? Are you looking for anything in particular?</label> 
                            <br>
                            <textarea id="feedback" name="feedback" rows="8" cols="50"></textarea>
                        </div>
                    </fieldset>
                    <fieldset>
                        <input type="reset" value="Reset" >
                        <input type="submit" value="Submit" >
                    </fieldset>
                </form>

Javascript

function validate(e){

    hideAllErrors();

    if(formHasErrors()){
        e.preventDefault();

        return false;
    }

    return true;
}

function resetForm(e){
    
    if ( confirm('reset?') )
    {
    
        hideAllErrors();
        
        document.getElementById("firstname").focus();
        
        return true;
    }

    e.preventDefault();

    return false;
}

function showError(formField, errorId, errorFlag){
    
    document.getElementById(errorId).style.display = "block";
    
    if ( !errorFlag )
    {
        
        formField.focus();
        
        if ( formField.type == "text" )
        {
            
            formField.select();
        }       
    }
}

function formHasErrors(){
    
    let errorFlag = false;

    let requiredFields = ["firstname","lastname","phonenum","email"];

    for(let i=0; i<requiredFields.length; i++){
        let textField = document.getElementById(requiredFields[i]);
        if(!formFieldHasInput(textField)){
            document.getElementById(requiredFields[i] + "_error").style.display = "block";

            if(!errorFlag){
                textField.focus();
                textField.select();
            }

            errorFlag = true;
        }
    }

    let regex = new RegExp(/^\d{6}$/);

    let phoneNumValue = document.getElementById("phonenum").value;

    if(!regex.test(phoneNumValue)){
        document.getElementById("phonenum_error").style.display = "block";

        if(!errorFlag){
            document.getElementById("phonenum").focus();
            document.getElementById("phonenum").select();
        }

        errorFlag = true;
    }

    return errorFlag;
}

function hideAllErrors(){
    
    let errorFields = document.getElementsByClassName("error");
    for(let i=0; i<errorFields.length; i++){
        errorFields[i].style.display = "none";
    }
}

function trim(str){
    
    return str.replace(/^\s+|\s+$/g,"");
}

function formFieldHasInput(fieldElement){
    
    if ( fieldElement.value == null || trim(fieldElement.value) == "" )
    {
        
        return false;
    }
    
    
    return true;
}

function load(){
    
    document.getElementById("contactus").addEventListener("submit", validate);

    document.getElementById("contactus").reset();

    document.getElementById("contactus").addEventListener("reset", resetForm);
}

document.addEventListener("DOMContentLoaded", load);

thanks in advance, struggling self learner

I've tried changing around tags and changing ids or classes around.

javalava
  • 23
  • 5
  • Does this answer your question? [Preventing form submission when input field is empty](https://stackoverflow.com/questions/15953988/preventing-form-submission-when-input-field-is-empty) – Garv Apr 21 '23 at 12:14

0 Answers0