I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)

I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?

Current HTML:

<div class="form-group" id="stage1">
   <div class="row">


        <input type="text" id="firstname" class="form-control" placeholder="Firstname*">  
        <input type="text" id="lastname" class="form-control" placeholder="Lastname*">
        <input type="email" id="email" class="form-control" placeholder="E-mail*">

        <input type="text" id="regnr" class="form-control" placeholder="Registration number">


    </div>
</div

I can't use HTML default validation, since I have created a multi-step form.

Thanks in advance,

Brandon

You can iterate through inputs this will assist validating your messy items:

window.onload = () => {
    const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
    let isAllvaild = true;
    allInputs.forEach((element) => {
        if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
    });
    if (isAllvaild) {
        afterValidation(); // to keep things clean 
    }
}

function validateAll(value, type) {
    if (type === "text") {

    } else if (type === "email") {
        var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
        let ck = re.test(String(value).toLowerCase());
        if (ck) {
            // set errors here..

        } else {
            // maybe remove errors if added previously..
        }
        return ck;

    } else if (type === "phone") {

    } else if (type === "other") {

    } // add whatever needed..
}

function afterValidation() {
    // at this point each input contains valid data.. proceed to next step.. 
    // document.querySelector("#my_id").classList.add("display-block");
    // ..
}

Ava Max - So Am I [Official Music Video], So Am I Available Now Download/Stream: https://AvaMax.lnk.to/SoAmIID Subscribe for more Duration: 3:14 Posted: Mar 7, 2019 Create an account or log in to Instagram - A simple, fun & creative way to capture, edit & share photos, videos & messages with friends & family.

you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:

if(textValidation() && emailValidation()){
  submit()
}

emailValidation(){
  return email ? true : false
}

textValidation(){
  return text ? true : false
}

I (Kendrick Lamar song), noun, plural I's or Is, i's or is. the ninth letter of the English alphabet, a vowel. any spoken sound represented by the letter I or i, as in big, nice, or ski. something� I or i is the ninth letter and the third vowel letter of the modern English alphabet and the ISO basic Latin alphabet. Its name in English is i (pronounced / ˈaɪ /), plural ies.

What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?@.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)

    function validateInputs ()
    {
        const inputs = document.querySelectorAll('div[class=row] input');

        for (let index = 0; index < inputs.length; index++)
        {
            const input = inputs[index];
            let valid = false;

            if (input.value && input.value.trim() !== '')
            {
                //here you can add specific validations for each id, maybe you can also use switch here
                if (input.getAttribute('id') === 'email')
                {
                    //of course, email also need to validate, if dot is present, regular expression might be the best option
                    if (input.value.indexOf('@') !== -1)
                    {
                        valid = true;
                    }
                }
                else
                {
                    valid = true;
                }
            }

            if (!valid)
            {
                input.classList.add('error');
            }
            else
            {
                input.classList.remove('error');
            }
        }
    };

    window.addEventListener('load', function () {
        document.querySelector('button').addEventListener('click', validateInputs)
    });
input.error {
    background-color: red;
}
<div class="row">

    <input type="text" id="firstname" class="form-control" placeholder="Firstname*">  
    <input type="text" id="lastname" class="form-control" placeholder="Lastname*">
    <input type="email" id="email" class="form-control" placeholder="E-mail*">

    <input type="text" id="regnr" class="form-control" placeholder="Registration number">

</div>

<button>validate</button>

I, Create an account or log in to Instagram - A simple, fun & creative way to capture, edit & share photos, videos & messages with friends & family. Definition of -i- (Entry 8 of 8) —used as a connective vowel to join word elements especially of Latin origin matrilineal raticide me or I ?: Usage Guide Example Sentences Learn More about i

For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.

Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.

const form = document.querySelector('form');
form.addEventListener('input', event => {
  if (form.checkValidity() === false) {
    const invalids = form.querySelectorAll(':invalid');
    for (const input of invalids) {
      console.log(`${input.id} is invalid`);
    }
  }
});
<form>
  <input type="text" id="firstname" class="form-control" placeholder="Firstname*">  
  <input type="text" id="lastname" class="form-control" placeholder="Lastname*">
  <input type="email" id="email" class="form-control" placeholder="E-mail*">
  <input type="url" id="website" class="form-control" placeholder="Website*">
  <input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>

Instagram, I definition is - the 9th letter of the English alphabet. How to use i in a sentence. me or I? Out now on iTunes: http://smarturl.it/iKL Google Play: http://smarturl.it/iKLgp Amazon: http://smarturl.it/iKLamz Best of Kendrick Lamar: https://goo.gl/PTr3

You can use this code between a script tag :

const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });

Or use a Bootstrap classes to validate your form

I, The ninth letter of the basic modern Latin alphabet. I (lower case ı). The letter i without a dot above, in both the upper case and the lower case versions. Ï, lowercase ï, is a symbol used in various languages written with the Latin alphabet; it can be read as the letter I with diaeresis or I-umlaut.

I, Windows is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. Mac is a trademark of Apple Inc. Log in to i-Ready®, online assessment and instruction that helps teachers provide all students a path to proficiency and growth in reading and mathematics.

[PDF] Employment Eligibility Verification Form I-9, I-94 is a place for U.S. visitors to find travel records. Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.

I94, Huge Selection - Rent or Buy Today! New Releases, Bestsellers & More.

Comments
  • type="email", type="text" how many different types are there among your 40+ inputs?
  • I think, it would be like 3 or 4.
  • I like this way, how would I proceed when every element returns true? True meaning it's valid.
  • depends on what you want to do after that, maybe you want to submit your form or whatever you need..
  • I want to proceed to the next page, since it is a multi step form. So when all inputs are valid, i would like to set some class display to none, and another class to display block.
  • just do it when all validation call return true, using a flag variable to indicate that all returned true, make another function maybe, liek afterValidation() and then just add/remove class or manipulate fields
  • Would it be smart to create an array of errors, and with the afterValidation function, i would iterate through those, applying border-color to wrong fields, and if no errors are there, proceed?
  • Doesn't exactly serve the goal. I need a way to find the inputs that are invalid, and since the form is over 40 questions, it seems odd to do this this way. Thanks anyway