简体   繁体   English

使用Java脚本进行验证

[英]Validation using java script

I am trying to give validation to both fields email and name but only email is getting validated and its not checking for name field. 我正在尝试对电子邮件和姓名这两个字段进行验证,但是只有电子邮件正在得到验证,并且不检查姓名字段。 I am not able to find what is wrong in the code. 我无法找到代码中的错误。

<html>
<body>
  <form name="myForm">
    Email: <input type="text" name="email" id="email2">
    <br>
    Name: <input type="text" name=" fname">
    <button type="submit" name="submit" onclick="validateForm()">submit</button>
    <br> email
    <div id="email1"></div>
  </form>
</body>
<script>
  function validateForm() {
    var x = document.forms["myForm"]["email"].value;

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

    var email1 = document.getElementById("email2").value;

    document.getElementById("email1").innerHTML=email1;

    var y = document.forms["myForm"]["fname"].value;
    if (y==null ||y=="") {
      alert("name must be filled");
      return false;    
    }
  }
</script>
</html>

You have missed giving id to Name: <input type="text" name=" fname"> Assign ID to Name: <input type="text" name=" fname" id="fname"> . 您已经错过了给Name分配ID: <input type="text" name=" fname"> ID分配ID Name: <input type="text" name=" fname" id="fname">

As document.forms["myForm"]["fname"].value; 作为document.forms["myForm"]["fname"].value; this requires element id to fetch value. 这需要元素id来获取值。

<input type="text" name=" fname">

fname前面有一个空格,这就是为什么它不起作用的原因。您可以尝试这样的简单解决方案

Add an additional boolean to check your validation 添加其他布尔值以检查您的验证

function validateForm() {
    var x = document.forms["myForm"]["email"].value;
    //Additional boolean
    var success = true;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
        success = false;
    }
   var email1= document.getElementById("email2").value;
       document.getElementById("email1").innerHTML=email1;

     var y = document.forms["myForm"]["fname"].value;
        if (y==null ||y=="") {
            alert("name must be filled");
            success = false;

    }
    return success;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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