简体   繁体   中英

Form Validation not working - javascript

I am trying to implement form validation so that when the submit button is hit, all required fields are filled. here is my code:

function checkInput()
{
    <!--check if these input values are provided -->
    var inputFile = document.getElementByID('inputFile').value;
    var numThreads = document.getElementById('numThreads').value;
    var scoreThresh = document.getElementById('scoreThresh').value;
    var scorePen = document.getElementById('scorePenalty').value;

    if(inputFile==="" ||numThreads==="" ||scoreThresh==="" ||scorePen==="" )
    {
        alert('Please fill in all required fields');

    }

//how i decalare the form

 <form  method =POST id="weVoteForm" onsubmit="return checkInput()">

this code isnt working however. Can anyone clarify what is wrong? Thanks!

You need to call the checkInput function before submitting the form. For this you can use onsubmit event in the form element as.

<form method="POST" id="weVoteForm" onsubmit="return checkInput();">
</form>

Your function should look like this

function checkInput()
{

    //check if these input values are provided -->
    // notice not <!-- in JS for comment and Id not ID
    var inputFile = document.getElementById('inputFile').value;
    var numThreads = document.getElementById('numThreads').value;
    var scoreThresh = document.getElementById('scoreThresh').value;
    var scorePen = document.getElementById('scorePenalty').value;

    if(inputFile==="" ||numThreads==="" ||scoreThresh==="" ||scorePen==="" )
    {
        alert('Please fill in all required fields');
        return false;
    }
  return true;
}

Moreover you can set required attribute in each element without having you to write this code as.

<input type="text" required />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM