使用 Jquery onclick 按钮进行表单验证

Form validation using Jquery onclick button

我在 jQuery 中为我的表单编写了验证码。一切似乎都是正确的,但它不起作用。帮帮我!

HTML 表格:

<form role="form" name="form1" id="form1">
    <div class="form-group">
        <label for="usr">Contact Name</label>
        <input type="text" name="usr" class="form-control" id="usr" placeholder="Full Name">
    </div>
    <div class="form-group">
        <label for="pwd">Company Name</label>
        <input type="text" class="form-control" id="pwd" placeholder="Company Name">
    </div>
    <div class="form-group">
        <label for="eml">Email</label>
        <input type="email" class="form-control" id="eml" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="phn">Contact Number</label>
        <input type="number" class="form-control" id="phn" placeholder="98689-98689">
    </div>
    <div class="form-group">
        <label for="comment">Remarks</label>
        <textarea class="form-control" rows="3" id="comment"></textarea>
    </div>
    <button id="submtbtn" style="height:30px ; width:60px;   padding: 5px 5px;" type="button" class="btn btn-info" onClick="AddNew(); this.form.reset()">Insert</button>
    <button style="height:30px ; width:60px;   padding: 5px 5px;" type="button" class="btn btn-info" onClick="this.form.reset()">Clear</button>
    <button id="cnclbtn" style="height:30px ; width:60px;   padding: 5px 5px;   background-color: #f1f1f1; " type="button" class="btn btn-default">Cancel</button>
</form>

这是验证脚本:

$(document).ready(function () {
    $("#form1").validate({
        rules: {
            usr: "required",
            pwd: "required",
            eml: {
                required: true,
                email: true
            },
            phn: {
                required: true,
                minlength: 10
            }
        },
        messages: {
            usr: "Please enter your first name",
            pwd: "Please enter your last name",
            eml: {
                required: "Please provide Email address ",
                email: "Please enter valid Email address"
            },
            phn: {
                required: "Please provide a Phone Number",
                minlength: "Your Phone Number must be 10 digits"
            }
        }
    });

    $("#submtbtn").click(function () {
        $("#form1").valid();
    });
});

错误之处请指出。谢谢。

JSFiddle https://jsfiddle.net/cherry1993/vwo0r0h6/

your jsFiddle 中,从 JavaScript 窗格中删除 <script></script> 标记并包括 jQuery 和 jQuery 之后验证插件,它开始工作...但仅适用于 usr 字段。

https://jsfiddle.net/vwo0r0h6/2/

它不适用于任何其他字段,因为您忘记在这些输入元素上包含 name 属性。此插件仅使用 name 属性,不使用 id 来跟踪表单输入。

<input type="text" class="form-control" name="pwd" placeholder="Company Name">

工作演示:https://jsfiddle.net/vwo0r0h6/3/


奖金:

您不必担心自定义消息中的值是否与规则的参数匹配。只需在自定义消息中使用参数的占位符 {0},它的值就会动态输入。请参阅上面的工作演示。

minlength: "Your Phone Number must be {0} digits"