Javascript没有正确验证表单。没有用户输入显示警报

时间:2013-12-26 00:26:54

标签: javascript html forms validation

问题

我尝试使用下面的javascript验证此表单,但即使我没有输入任何值,警报也只会显示一次,然后表单将被提交并创建文件。


的Javascript

function validateForm() {
    console.log('the code is running');
    var firstName = document.forms.["myForm"]["firstName"].value;
    var lastName = document.forms["myForm"]["lastName"].value;
    var gender = document.forms["myForm"]["Gender"].value;
    var eMail = document.forms["myForm"]["Email"].value;
    var phoneNumber = document.forms["myForm"]["phoneNumber"].value;
    var information = document.forms["myForm"]["information"].value;

    if (firstName === null || firstName === ""){
          prompt("Please enter your First Name.");
          return false;
    }
    if (lastName == null || lastName == ""){
          alert("Please enter your Last Name.");
          return false;
    }
    if (gender == null){
          alert("Please Click on the button next to your gender");
          return false;
    }

    var atpos = eMail.indexOf("@");
    var dotpos = eMail.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= eMail.length){
          alert("Not a valid e-mail address");
          return false;
      }
}

PHP / HTML

<?php 
    if($_POST['submitForm'] == 'submit' ){
        echo "the Form has been submitted";
        $filename = $_POST['firstName'] . ".txt";
        $current = $_POST['firstName'] . "\r\n" . $_POST['lastName'] . "\r\n" . $_POST['Gender'] . "\r\n" . $_POST['Email'] . "\r\n" . $_POST['phoneNumber']
        . "\r\n" . $_POST['information'];
        file_put_contents($filename, $current);
    } 
?>

<form action="" name ="myForm" method=" post"onsubmit="javascript:return validateForm()">
    <table>
        <tr>
            <td>First Name:</td>
            <td>
                <input type="text" name="firstName" maxlength="25" autofocus>
            </td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td>
                <input type="text" name="lastName" maxlength="25">
            </td>
        </tr>
        <tr>
            <td>Gender:</td>
            <td>
                <input type="radio" name="Gender" value="male">Male
                <input type="radio" name="Gender" value="female"> Female
            </td>
        </tr>
        <tr>
            <td>Email:</td>
            <td>
                <input type="email" name="Email" maxlength="35">
            </td>
        </tr>
        <tr>
            <td>Phone Number:</td>
            <td>
                <input type="tel" name="phoneNumber" maxlength="20">
            </td>
        </tr>
        <tr>
            <td>Ask question and provide background information</td>
            <td>
                <textarea name="information" rows="5" cols="20" placeholder="put your question and background information here"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" name="submitForm" value="submit" onclick="javascript:return validateForm()"><input type="reset" value="reset"></td>
        </tr>
    </table>
</form>

3 个答案:

答案 0 :(得分:0)

你有几个错别字;您有lastNmae而不是lastName。此外,只需将提交按钮设为按钮并移除onSubmit()事件处理程序,然后通过javascript form.submit()

调用它
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
    <link href="newcss.css" rel="stylesheet">

</head>
<body>

    <script type="text/javascript"> 
        function validateForm()
        {
            console.log('the code is running');
            var firstName = document.forms.["myForm"]["lastName"].value;
            var lastName = document.forms["myForm"]["Gender"].value;
            var gender = document.forms["myForm"]["Gender"].value;
            var eMail = document.forms["myForm"]["Email"].value;
            var phoneNumber = document.forms["myForm"]["phoneNumber"].value;
            var information = document.forms["myForm"]["information"].value;


            if (firstName === null || firstName === ""){
                prompt("Please enter your First Name.");
                return false;
            }

            if (lastName == null || lastName == ""){
                alert("Please enter your Last Name.");
                return false;
            }

            if (gender == null){
                alert("Please Click on the button next to your gender");
                return false;
            }

            var atpos = eMail.indexOf("@");
            var dotpos = eMail.lastIndexOf(".");

            if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= eMail.length){
                alert("Not a valid e-mail address");
                return false;
                }

        }
    </script>

        <?php if($_POST['submitForm'] == 'submit' ){
                    echo "the Form has been submitted";
        $filename = $_POST['firstName'] . ".txt";
        $current = $_POST['firstName'] . "\r\n" . $_POST['lastName'] . "\r\n" . $_POST['Gender'] . "\r\n" . $_POST['Email'] . "\r\n" . $_POST['phoneNumber']
            . "\r\n" . $_POST['information'];
        file_put_contents($filename, $current);
            } 
        ?>

        <form action="" name ="myForm" method="post">

            <table>
                <tr>
                    <td>First Name:</td>
                    <td><input type="text" name="firstName" maxlength="25" autofocus></td>
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type="text" name="lastName" maxlength="25"></td>
                </tr>
                <tr>
                    <td>Gender:</td>
                    <td><input type="radio" name="Gender" value="male">Male
                        <input type="radio" name="Gender" value="female"> Female
                    </td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input type="email" name="Email" maxlength="35"></td>
                </tr>
                <tr>
                    <td>Phone Number:</td>
                    <td><input type="tel" name="phoneNumber" maxlength="20"></td>
                </tr>
                <tr>
                    <td>Ask question and provide background information</td>
                    <td><textarea name="information" rows="5" cols="20" placeholder="put your question and background information here"></textarea></td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" name="submitForm" input type="button" onclick="validateForm();"/><input type="reset" value="reset"></td>
                </tr>
            </table>
        </form>

    </div>   
</body>
</html>

答案 1 :(得分:0)

除了scrblnrd3的答案,要获得性别的价值,您需要以下内容:

 <td>Gender:</td>
 <td><input type="radio" name="Gender" value="male">Male
     <input type="radio" name="Gender" value="female"> Female
 </td>


var genderButtons = form.Gender;
var genderValue;

for (var i=0, iLen=genderButtons.length; i<iLen; i++) {

  if (genderButtons[i].checked) {
    genderValue = genderButtons[i].value;
  }
}

if (!genderValue) {
  // no gender button selected
}

答案 2 :(得分:0)

因为您可以自己调试它并半让它再次运行。你还需要一个函数来阻止表单提交,那就是event.preventDefault()

function validateForm (e) {
  // stops the form submitting
  (e || window.event).preventDefault();
  ...
  // all code in between

  ...
  document.forms["myForm"].submit();
}

并且在你的html中它就像调用函数一样简单,你不需要添加javascript也不需要返回;

<form ... onsubmit="validateForm()" ... >

顺便删除括号document.forms.["myForm"]前面的点到document.forms["myForm"]

编辑:解决单选按钮验证

你的HTML中的

// avoid a null value by having a default value using checked attribute
<input type="radio" id="isMale" checked ... > Male
<input type="radio" id="isFemale" ... > Female
你的javascript中的

用这个

替换你当前的验证
...
var isMale   = document.getElementById('isMale')
,   isFemale = document.getElementById('isFemale');
...
if (!isMale.checked && !isFemale.checked) {
  // user hasn't checked male nor female
  alert("Please Click on the button next to your gender");
  return false;
}
...

http://jsfiddle.net/7rp88/