无法验证电子邮件和号码

时间:2017-07-04 13:01:46

标签: javascript html forms validation

我需要帮助,因为我已将以下javascript(在下面的代码中提到)添加到我的表单中,并且我将ID传递给js,但无法验证它。

Javascript代码

function validateForm() {
    var x = document.getElementById('emailid').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 txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}

HTML

<div class="form-group">
    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
<div class="form-group">
    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>

3 个答案:

答案 0 :(得分:0)

您的代码存在很多错误......

首先,您的HTML无效,因为您的label元素具有for属性的值,这些属性未指向它们所属元素的id属性值&#34;对于&#34 ;.

此外(也许你确实拥有它但未在你的问题中显示它),你没有包含所有输入的form元素。

现在,由于您在HTML中使用input type=emailrequired,因此您将自动获得验证。如果您只是将pattern属性添加到您的手机字段中,则您不需要任何JavaScript来验证,因为这是内置的。使用内置的电子邮件字段然后编写以相同方式验证的电子邮件验证代码毫无意义。

&#13;
&#13;
<form action="#" method="post">
       <div class="form-group">
          <!-- There's no need to set value="" on a text field when you want it to start blank -->
          <!-- When you use the HTML validation fields and attributes, you don't need JavaScript
               unless you want to implement custom validation.      -->
          <input type="email" required class="form-control" 
                 placeholder="Email ID" id="emailid" name="Email"  maxlength="70">
          <!-- The "for" attribute of a label must point to the ID of the element it is for -->
          <label class="input-field-icon icon-email" for="emailid"></label>
       </div>
       <div class="form-group">
          <input type="text" class="form-control" pattern="([0]|\+91|\+91-|\+91\s)?\d{10}" required
                 placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">
          <!-- You had a copy of the email label down here -->
          <label class="input-field-icon" for="mobNo"></label>
       </div>
       <div>
         <input type="submit" value="Submit"><input type="reset">
       </div>
</form>
&#13;
&#13;
&#13;

如果您确实想编写自己的验证代码,那么您将返回使用非验证表单字段或HTML5自定义验证。假设情况就是这样......

您的验证功能从未被调用过。它必须是&#34;有线&#34;直到事件,以便在事件发生时,将自动调用该函数。这被称为&#34;回调函数&#34;。由于您正在使用form(或应该是),因此表单将包含submit事件,这是进行表单验证的适当时间。

此外,您的电子邮件验证逻辑存在缺陷(例如,允许使用me.you@的电子邮件地址)。

这里的代码应该是什么样子。我已经删除了HTML验证,以便您可以看到JavaScript正在完成其工作。

请阅读代码中的注释,了解正在做什么以及原因:

&#13;
&#13;
// Don't mix HTML and JavaScript (as others have suggested). Keep them separate

// All this code should be placed inside of a <script> element and the entire thing
// should be placed just before the end of the body element (</body>) so that by the 
// time this code runs all the HTML will have been read into memory.

// Get a reference to the elements you'll need to work with
var frm = document.querySelector("form");
var email = document.getElementById("emailid");
var mobNum = document.getElementById("mobNo");

// Set the form up to have a submit event callback function
// This is what makes it so that when your form is submitted,
// your validation function runs.
frm.addEventListener("submit", validateForm);

// This function will now be automatically called when the form is submitted
// All event handling functions will automatically be passed a reference to 
// the event they are responding to and that reference will be passed as the
// first argument to the funciton (we are receiving that reference with the
// "evt" argument here).
function validateForm(evt) {
 
  // validate the email input with a regular expression
  var emailExpr = /^(([^<>()\[\]\\.,;:\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,}))$/;
  
  // validate the phone number with a regular expression
  var mobNumExpr = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;

  // Assume the form is valid
  var valid = true;

  // Test the input. Always call the trim() string method on user input as it
  // will strip off any leading or trailing spaces.
  if(!emailExpr.test(email.value.trim())){ 
     // Bad email.
     valid = false;
     alert("Bad email");
  }
  
  // Test to see if the email is good and the mobile is bad
  if(valid && !mobNumExpr.test(mobNum.value.trim())){
     valid = false;
     alert("Bad mobile number");
  }
  
  // If something has set the form to be invalid....
  if(!valid){
     evt.preventDefault();  // Cancel the event (don't submit the form)
     evt.stopPropagation(); // Prevent the event from bubbling
  }
  
}
&#13;
<form action="#" method="post">
   <div class="form-group">
      <!-- There's no need to set value="" on a text field when you want it to start blank -->
      <input type="text" class="form-control" 
             placeholder="Email ID" id="emailid" name="Email"  maxlength="70">
      <!-- The "for" attribute of a label must point to the ID of the element it is for -->
      <label class="input-field-icon icon-email" for="emailid"></label>
   </div>
   <div class="form-group">
      <input type="text" class="form-control" 
             placeholder="Mobile Number" id="mobNo" name="number" maxlength="14">
      <!-- You had a copy of the email label down here -->
      <label class="input-field-icon" for="mobNo"></label>
   </div>
   <div>
     <input type="submit" value="Submit"><input type="reset">
   </div>
</form>
&#13;
&#13;
&#13;

最后,无论您如何实现客户端验证,您都必须始终记住,任何希望绕过它的人都可以轻松绕过它,所以在接受数据之前,您应该始终在服务器端重复验证。

答案 1 :(得分:-1)

如果您将使用表单标签来验证此数据,则可以使用onsubmit属性。

Here is documentation

否则,如果您想为表单使用事件处理程序,您可以传递事件数据,并在表单无效时阻止它。

Here is some usefull information

答案 2 :(得分:-1)

您可以使用正则表达式轻松验证用户输入。确保在提交表单时调用您的JavaScript。

HTML

<form onSubmit="myFunction()">
Email Address: <input type="email" id="userEmail" name="email" placeholder="Enter a valid email address" required>
</form>

的JavaScript

function myFunction(){
 var email = document.getElementById('userEmail').value;
 if(/^(([^<>()\[\]\\.,;:\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,}))$/.test(email)){
    alert('Valid');
 }else{
    alert('Invalid');
 }
} 

结果

Input: 'email@email.com' Result: 'Valid"  
Input: 'email@email'     Result: 'Invalid'