简体   繁体   中英

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 ). Is there any possibility?any help would be appreciated..

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

Use this

JS

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

DEMO

Note: HTML5 required attribute may not work on all browsers.

where there is your < form > tag in html add this attribute

example:

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

and then write this jquery function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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