使用Jquery验证表单

时间:2017-11-06 11:26:24

标签: javascript jquery html

有没有人知道为什么这段代码不起作用?它只是在提交时将我带到“未找到”页面。我从Learning Jquery.com复制了大部分内容,但它仍无效。我的id和名字匹配,所以它不可能。该网站确实说我可能要下载JQuery库,但肯定只是链接到库也可以。 第一个片段是Jquery,第二个是我的CSS,第三个是我的HTML(在那里你可以看到我用来链接到JQuery库的src。

$("#contactForm").validate({
  //specify the validation rules
  rules: {
    firstname: "required",
    lastname: "required",
    email: {
      required: true,
      email: true //email is required AND must be in the form of a valid email address
    },
    password: {
      required: true,
      minlength: 6
    }
  },

  //specify validation error messages
  messages: {
    firstname: "First Name field cannot be blank!",
    lastname: "Last Name field cannot be blank!",
    password: {
      required: "Password field cannot be blank!",
      minlength: "Your password must be at least 6 characters long"
    },
    email: "Please enter a valid email address"
  },

  submitHandler: function(form) {
    form.submit();
  }

});
.form-container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

form .error {
  color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<div class="form-container">
  <h2>Registration</h2>
  <form action="#" name="contactForm" id="contactForm">
    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="John" />

    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe" />

    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="john@doe.com" />

    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />

    <button type="submit">Submit</button>
  </form>

2 个答案:

答案 0 :(得分:0)

您需要包含Jquery库引用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

答案 1 :(得分:0)

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>   <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

尝试导入这个jQuery lib。