iT邦幫忙

DAY 23
2

JSP 學習分享系列 第 23

JSP 和Regular Expressions

有人建議使用Regular Expressions 來檢查input資料,於是就去找了一些SourceCode,
以下是第一個可以正確執行無誤的範例
=== login.jsp ===

    <title>Login</title>
    <script type="text/javascript">

      var RE_EMAIL = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;
      var RE_PASSWORD = /^[A-Za-z\d]{6,8}$/;

      function validate(form){
        var email = form.Email.value;
        var password = form.Password.value;
        var errors = [];

        if (!RE_EMAIL.test(email)) {
          errors[errors.length] = "You must enter a valid email address.";
        }

        if (!RE_PASSWORD.test(password)) {
          errors[errors.length] = "You must enter a valid password.";
        }

        if (errors.length > 0) {
          reportErrors(errors);
          return false;
        }

        return true;
      }

      function reportErrors(errors){
        var msg = "There were some problems...\n";
        for (var i = 0; i<errors.length; i++) {
          var numError = i + 1;
          msg += "\n" + numError + ". " + errors[i];
        }
        alert(msg);
      }
    </script>
  
  
    <h1>Login Form</h1>
    <form method="post" action="main.jsp" onsubmit="return validate(this);">

      Email: <input type="text" name="Email" size="25"><br/>
      Password: <input type="password" name="Password" size="10"><br/>
      *Password must be between 6 and 10 characters and
      can only contain letters and digits.<br/>

      <input type="submit" value="Submit">
      <input type="reset" value="Reset Form">

    </form>
  

上一篇
在JSP 如何使用switch
下一篇
JSP and ERROR Page應用
系列文
JSP 學習分享30

尚未有邦友留言

立即登入留言