iT邦幫忙

DAY 21
5

JSP 學習分享系列 第 21

JSP 和validate email

JSP 和validate email,
使用javascript 檢查email是否合法,可以初步過濾一些亂打的使用者
使用javascript 檢查email是否合法,可以初步過濾一些亂打的使用者
=== valid_email.jsp ===

<HTML>
  <HEAD>
  <TITLE>check valid email</TITLE>
  </HEAD>
  <BODY>
  <script type="text/javascript">
    /* This is code to check valid email using java script. */
    function emailCheck(str) {

      var at="@"
      var dot="."
      var lat=str.indexOf(at)
      var lstr=str.length
      var ldot=str.indexOf(dot)
      // check if '@' is at the first position or   at last position or absent in given email
      if (str.indexOf(at)==-1 || str.indexOf(at)==0 ||
        str.indexOf(at)==lstr){
        alert("Invalid E-mail ID")
        return false
      }

      // check if '.' is at the first position or at last    position or absent in given email
      if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 ||
        str.indexOf(dot)==lstr){
        alert("Invalid E-mail ID")
        return false
      }

      // check if '@' is used more than one times in given email
      if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID")
        return false
      }


      // check for the position of '.'
      if (str.substring(lat-1,lat)==dot ||
        str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID")
        return false
      }

      // check if '.' is present after two characters  from location of '@'
      if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID")
        return false
      }

      // check for blank spaces in given email
      if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID")
        return false
      }
      return true
    }

    function ValidateForm(){
      var emailID=document.form.txtEmail
      //check if email is not entered or only spaces    are entereds in appropriate textbox
      if ((emailID.value==null)||(emailID.value=="")){
        alert("Please Enter your Email ID")
        // set cursor to the textbox provided for email entry
        emailID.focus()
        return false
      }
      if (emailCheck(emailID.value)==false){
        emailID.value=""
        emailID.focus()
        return false
      }
      return true
    }
    </script>
    <form name="form" method="post" onSubmit="return ValidateForm()" action="valid_email.jsp">
      <p>Enter an Email Address <input type="text" name="txtEmail"></p>
      <p> <input type="submit" name="Submit" value="Submit"></p>
    </form>
    <%
    String txtmail = request.getParameter("txtEmail");
    if(txtmail!=null  ){
      %>this mail <%=txtmail%> is validate.<%
      }
    %>
  </BODY>
</HTML>

上一篇
JSP 和資料庫和 html Table的範例
下一篇
在JSP 如何使用switch
系列文
JSP 學習分享30

2 則留言

0
fillano
iT邦超人 1 級 ‧ 2009-11-02 11:00:02

這樣用indexOf來檢查太麻煩了吧,用Regular Expression一行就可以解決耶?

好啊,找時間再研究一下

0
kbslave
iT邦新手 4 級 ‧ 2009-11-02 12:16:41

完全同意... 推RE

我要留言

立即登入留言