使用Jquery和没有validate.js文件验证表单

时间:2015-06-18 12:41:07

标签: jquery html validation

我正在尝试使用jquery实现验证。但不知道我在哪里做错了。以下是我的代码。请帮忙。

<script type="text/javascript">
$(document).ready(function() {
    alert("ready");
})
$("#myForm").validate({
    rules: {
        txt: {
            required: true,
            minLength: 2,
        }
    },
    messages: {
        txt: {
            required: "Enter your text",
            minLength: "At least 2 characters are necessary",
        }
    }
});
</script>
<form action="" id="myForm">
    <p>
        <input type="text" id="txt" placeholder="Input" />
    </p>
    <p>
        <input type="submit" id="sbmt" value="Submit Button" />
    </p>
</form>

2 个答案:

答案 0 :(得分:1)

将脚本转换为手动,我们得到:

$("#myForm").submit(function (e) {
  if ($(this).find("#rules").val().trim().length < 2) {
    alert("Rules length should be at least 2");
    return false;
  }
  if ($(this).find("#messages").val().trim().length < 2) {
    alert("Messages length should be at least 2");
    return false;
  }
});

答案 1 :(得分:0)

使用此代码可能会对您有所帮助。

<script type="text/javascript">
$(document).ready(function() {
  $("#myForm").validate({
    rules: {
        txt: {
            required: true,
            minLength: 2,
        }
    },
    messages: {
        txt: {
            required: "Enter your text",
            minLength: "At least 2 characters are necessary",
        }
    }
  });
});
</script>