/    Sign up×
Community /Pin to ProfileBookmark

Form Submit required fields

I’m using Javascript to submit a form as I’m also using reCaptcha v3. I understand (correct me if I’m wrong) the required atterribute doesn’t work when submitting a form via JS.

Therefore my required fields are not longer being validated and that’s the reason my form is being submitted without data in these required fields.

I’m doing something like this to overcome this.

If at the end of my JS validation ‘outcome’ is still 0 then the form submits.

My questions are

  • 1. This is very long script as I have 20 fields (stree address, town, city, zip, name, email, confirm email etc etc) Is there a shorter way of doing this?

  • 2. Is this the best way

  • 3. Am I correct with why my required fields are not working?
  • “`
    let outcome = 0;
    if (document.getElementById(“email”).value == “”) {
    document.getElementById(“emaillabel”).innerHTML = “Please complete Email”;
    document.getElementById(“emaillabel”).style.color = “red”;
    outcome = 1;
    } else {
    document.getElementById(“emaillabel”).style.color = ‘black’;
    }

    if (outcome == 0){
    document.getElementById(“myform”).submit();
    }
    “`

    to post a comment
    JavaScript

    6 Comments(s)

    Copy linkTweet thisAlerts:
    @cootheadAug 04.2020 — Hi there kiwis80,

    all form validation should be done server side.

    For client side use the the [b]required attribute[/b]

    to indicate the a form element requires content.

    [b]Example:-[/b]

    <i>
    </i>&lt;!DOCTYPE HTML&gt;
    &lt;html lang="en"&gt;
    &lt;head&gt;

    &lt;meta charset="utf-8"&gt;
    &lt;meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"&gt;

    &lt;title&gt;basic form&lt;/title&gt;

    &lt;/head&gt;
    &lt;body&gt;

    &lt;form action="#"&gt;
    &lt;label for="sname"&gt;Surname:&lt;/label&gt;&lt;br&gt;
    &lt;input id="sname" type="text" required&gt;&lt;br&gt;
    &lt;input type="submit" value="submit information"&gt;
    &lt;/form&gt;

    &lt;/body&gt;
    &lt;/html&gt;


    [i]coothead[/i]
    Copy linkTweet thisAlerts:
    @SempervivumAug 04.2020 — If you have 20 fields it's recommendable to use a loop in order to validate your form elements:
    let valid = true;
    const formElems = document.querySelectorAll('input, select');
    formElemns.forEach(formEle =&gt; {
    const lbl = document.querySelector('[for="' + formEle.id + '"]'];
    if (!formEle.validity.valid) {
    valid = false;
    lbl.style.color = 'red';
    } else {
    lbl.style.color = 'black';
    } <br/>
    }
    if (valid) {
    document.getElementById("myform").submit();
    }
    Benefit when using the property `validity.valid</C>: It will take into account any constraint you defined for the form element like required, pattern etc.<br/>
    Note: When styling the input itself, this can be done without Javascript by use of the pseudo class <C>
    :valid`
    :
    input:not(:valid) {
    color: red;
    }
    Copy linkTweet thisAlerts:
    @kiwisauthorAug 05.2020 — @Sempervivum#1621799

    I think the sound of this.

    I've tweaked it a little as not 100% of input's are mandatory by making the first like this querySelectorAll('.verify');

    In console.dir I get a nodelist of all the dirrect elements but you're code does not loop through them all and I don't get any error
    Copy linkTweet thisAlerts:
    @SempervivumAug 05.2020 — @kiwis80#1621803 In console.dir I get a nodelist of all the dirrect elements but you're code does not loop through them all and I don't get any error[/quote]If it doesn't work for all elements some debugging or analysing the code would be required, e. g. checking if a label is defined for all elements.
    Copy linkTweet thisAlerts:
    @LeonWilliamAug 06.2020 — thanks a lot
    Copy linkTweet thisAlerts:
    @rpg2009Aug 10.2020 — > @kiwis80#1621803 I've tweaked it a little as not 100% of input's are mandatory

    You can test to see if the field is **required** by checking the elements **required** attribute

    e.g.

    &lt;input type='email' class='form-control' id='inputEmail4' placeholder='Email' required&gt;

    A simple test with a form grabbed from the bootstrap page

    ``<i>
    </i>&lt;!DOCTYPE html&gt;
    &lt;html lang='en'&gt;
    &lt;head&gt;
    &lt;meta charset='UTF-8'&gt;
    &lt;meta name='viewport' content='width=device-width, initial-scale=1.0'&gt;
    &lt;title&gt;Form Test&lt;/title&gt;
    &lt;link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css'&gt;
    &lt;/head&gt;
    &lt;body&gt;
    &lt;div class='container'&gt;
    &lt;div class='col-6 mt-3'&gt;
    &lt;form id='test-form' action='' method='POST'&gt;
    &lt;div class='form-row'&gt;
    &lt;div class='form-group col-md-6'&gt;
    &lt;label for='inputEmail4'&gt;Email&lt;/label&gt;
    &lt;input type='email' class='form-control' id='inputEmail4' placeholder='Email' required&gt;
    &lt;/div&gt;
    &lt;div class='form-group col-md-6'&gt;
    &lt;label for='inputPassword4'&gt;Password&lt;/label&gt;
    &lt;input type='password' class='form-control' id='inputPassword4' placeholder='Password' required&gt;
    &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class='form-group'&gt;
    &lt;label for='inputAddress'&gt;Address&lt;/label&gt;
    &lt;input type='text' class='form-control' id='inputAddress' placeholder='1234 Main St' required&gt;
    &lt;/div&gt;
    &lt;div class='form-group'&gt;
    &lt;label for='inputAddress2'&gt;Address 2 (Optional)&lt;/label&gt;
    &lt;input type='text' class='form-control' id='inputAddress2' placeholder='Apartment, studio, or floor'&gt;
    &lt;/div&gt;
    &lt;div class='form-row'&gt;
    &lt;div class='form-group col-md-6'&gt;
    &lt;label for='inputCity'&gt;City&lt;/label&gt;
    &lt;input type='text' class='form-control' id='inputCity' required&gt;
    &lt;/div&gt;
    &lt;div class='form-group col-md-4'&gt;
    &lt;label for='inputState'&gt;State&lt;/label&gt;
    &lt;select id='inputState' class='form-control' required&gt;
    &lt;option selected&gt;Choose State&lt;/option&gt;
    &lt;option&gt;AL&lt;/option&gt;
    &lt;option&gt;AK&lt;/option&gt;
    &lt;option&gt;AZ&lt;/option&gt;
    &lt;/select&gt;
    &lt;/div&gt;
    &lt;div class='form-group col-md-2'&gt;
    &lt;label for='inputZip'&gt;Zip&lt;/label&gt;
    &lt;input type='text' class='form-control' id='inputZip' pattern='^d{5}(?:-d{4})?$' required&gt;
    &lt;/div&gt;
    &lt;/div&gt;
    &lt;button type='submit' class='btn btn-primary'&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
    &lt;/div&gt;
    &lt;/div&gt;
    &lt;/body&gt;

    &lt;script&gt;
    // make an array copy from the HTML collection elements
    // that way we can use all the array methods filter, find, map etc.
    const form = Array.from(document.querySelector('#test-form').elements)
    const requiredFields = form.filter(elem =&gt; elem.required === true)
    console.dir(requiredFields) // an array of only the required fields
    &lt;/script&gt;
    &lt;/html&gt;<i>
    </i>
    ``

    Worth noting as an alternative to accessing elements in a form with querySelector, a form comes with an HTML collection or HTMLFormControlsCollection called elements — an array-like object.

    You can access the elements in the form using this collection and an **index, id or name**. In the example above I have used Array.from() to copy that collection to an Array so that I then have access to Array's higher order functions like **map, filter, find** etc.

    The MDN Link for form.elements

    [https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements](url)
    ×

    Success!

    Help @kiwis spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.7,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...