为什么不能进行jquery验证?

时间:2017-06-23 11:37:48

标签: javascript jquery html validation

我有一个字段的表单,我通过jquery validation验证此字段。但是在所有情况下我的形式都是沙子,但在js我注入约束,验证不起作用。

帮我解决这个问题。谢谢。

这是form中的index.html

<head>
    <title>Form</title>

    <link href="style.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" />
    <script src="jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min‌​.js"></script>
    <script src="validation.js"></script>

</head>
<body>
    <div class="p-x-1 p-y-3">
        <form id="form" class="card card-block m-x-auto bg-faded form-width" method="POST" action="go" name="validation">
            <legend class="m-b-1 text-xs-center">Enter data</legend>

            <div class="form-group input-group">
                <span class="has-float-label">
                <input class="form-control" name="name" id="name" type="text" placeholder="Name"/>
                <label for="name">Name</label>
                </span>
            </div>

            <div class="text-xs-center">
                <button class="btn btn-block btn-primary" type="submit">Edit</button>
            </div>

        </form>
    </div>
</body>

这是用于验证的js脚本:

$(function() {
  // Form contain attribute name="registration".
  $("form[name='validation']").validate({
    rules: {
      name: {
        required: true,
        minlength: 5
      }
    },

    // Error message.
    messages: {
      name: "Error"
    },

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

我在jquery-validation的同一文件夹中有index.html个库。 enter image description here

2 个答案:

答案 0 :(得分:2)

请交换下面给出的两个脚本。

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="jquery-validation/dist/jquery.validate.min.js"></script>

当你使用jQuery插件时,它总是需要jQuery。在你的情况下,你首先添加了验证库,然后是jQuery,因此它没有用。

答案 1 :(得分:2)

您的代码按此顺序导入css和js

    <link href="style.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" />
    <script src="jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min‌​.js"></script>
    <script src="validation.js"></script>

但是你应该先导入jquery,然后再进行扩展,即jquery验证。我还建议在导入bootstrap组件文件之前使用jquery,以便更安全。因此,您正确的导入顺序将是: -

    <script src="src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min‌​.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css"/>
    <link href="style.css" rel="stylesheet">
    <script src="jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="validation.js"></script>

虽然这不在上下文中,但是,您应该在引导程序css文件之后导入自定义css。