简体   繁体   English

使用javascript验证表单字段的空电子邮件输入

[英]Validating empty Email input for form field using javascript

Html :网址:

<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)@(\w+\.)+(com|kr|net|us|info|biz)" required="required">

Script :脚本 :

<script type="text/javascript">
    function checkStatus() {
        var productcode = $("#Code").val();
        var productEmail = $("#Email").val();
        alert("email is== " + Email)

        if (!document.getElementById("Email").checkValidity()) {
            alert("Please Enter Valid Email Id");
            return false;

        } else {
            callMeIfValid();
        }

        document.getElementById('Email').value = '';    
    }

    function callMeIfValid() {    
        alert("valid input");    
    }
</script>

In the above code i am able to validate whether the email id given by user is valid or not based on the regex pattern inside input tag.But i Want to perform validation when the user submits an empty field( without any email input ).在上面的代码中,我能够根据输入标签内的regex模式验证用户提供的电子邮件 ID 是否有效。但是我想在用户提交空字段(没有任何电子邮件输入)时执行validation Is there any possibility?any help would be appreciated..有没有可能?任何帮助将不胜感激..

您可以首先使用 .val() 检查用户是否输入了任何文本或值,然后检查输入是否有效。

Use this用这个

JS JS

if(document.getElementById("Email").value=='')
{
  alert("Please Enter Email ID");
  return false;    
}

DEMO演示

Note: HTML5 required attribute may not work on all browsers.注意:HTML5 required属性可能不适用于所有浏览器。

where there is your < form > tag in html add this attribute在 html 中有你的 <form> 标签的地方添加这个属性

example:例子:

<form onsubmit="return validate();" bla bla bla>  // put onsubmit in your form tag

and then write this jquery function然后写这个jquery函数

function validate(){
    if($("#Email").val()=='')
    {
        alert("Please Enter Email ID");
        return false;    
    }
 }

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

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