JavaScript form onSubmit handling

三世轮回 提交于 2020-01-05 04:50:44

问题


I am new to JavaScript and have been searching the threads here but can't figure out why my forms are not running through the validation properly. I have tried adding alerts to find the issue, and it seems like it is somewhere around the first IF statement. Any ideas? Thanks!

<script type="text/javascript">

function dataCheck()
{
        var firstName = document.getElementById("firstName").value;
        var firstName = document.myForm.firstName.value;
        var lastName = document.getElementById("lastName").value;
        var facilitator = document.getElementById("facilitator").value;
        //validate firstName field for minimum of 2 characters
        if (firstName.length < 2){
            alert("Please enter a first name with a minimum of 2 characters");
            return false;
        }
        else {retvalue = true}
        //validate lastName field for min length and numeric or alpha characters only
        if (lastName.length < 2 || lastName.){
            alert("Please enter a last name with a minimum of 2 characters");
            return false;
        }
        if( /[^a-zA-Z0-9]/.test(lastName) ) {
            alert("Last name must be alphanumeric.");
            return false;
        }
}

</script>

<form action="http://bucs601.com/submit.php" name="myForm" onsubmit="return dataCheck()" method="post">
              First name: <input type="text" id="firstName" name="firstName"><br>
              Last name: <input type="text" id="lastName" name="lastName"><br>
              Email: <input type="text" id="email" name="email"><br>
              Facilitator: <input type="text" id="facilitator" name="facilitator">
              <input type="submit" id="submit" value="Submit">
</form>

回答1:


The one obvious error I can see is the incomplete line:

if (lastName.length < 2 || lastName.){

What is the second condition supposed to be? If I remove the "|| lastName." bit the function seems to work ok.




回答2:


Should Be like this :

replace if (lastName.length < 2 || lastName.){

With if (lastName.length < 2 || lastName){

remove ..



来源:https://stackoverflow.com/questions/14806594/javascript-form-onsubmit-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!