为什么JS函数不起作用?

时间:2018-08-12 17:25:48

标签: javascript

我不熟悉Spring MVC和静态Web资源并尝试重建项目,但是如果有人可以向我解释为什么JS函数不起作用,我会遇到问题?

关于项目(使用Spring Boot框架的Spring MVC Web应用程序。并使用JSP作为Web应用程序的视图)。

app.js

function validate() {
    var name = document.getElementById("name").value;
    if (name == '') {
        alert('Please enter a valid name.');
        return false;
    } else {
        return true;
    }
}

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<!-- Static content -->

<link href="${pageContext.request.contextPath}/resources/css/style.css" rel="stylesheet" >
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/app.js"></script>
<title>SchoolApp</title>
</head>
<body>
  <h1>Spring Boot - MVC design</h1>
  <hr>

  <div class="form">
    <form action="hello" method="post" onsubmit="return validate()">
      <table>
        <tr>
          <td>Enter Your name</td>
          <td><input id="name" name="name"></td>
          <td><input type="submit" value="Submit"></td>
        </tr>
      </table>
    </form>
  </div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

jQuery验证插件解决了问题

jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");

$(document).ready(function () {

    $('form').validate({ // initialize the plugin
        rules: {
            name: {
                required: true,
                lettersonly: true,
            }
        }
    });

});