繁体   English   中英

使用Jquery进行表单验证

[英]Form Validation using Jquery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Validation POC</title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    $("#frm").validate({
        rules: {
            cname: {
                required: true
            },
            cemail: {
                required: true,
                email: true
            }
        },
        messages: {
            cname: "Please
    enter
    your
    name",
            cemail: {
                "Email
    is
    not
    validated"
            }
        }
    });
});
</script>
</head>
<body>
<form id="frm" action="" method="get">
 <fieldset>
   <legend>Validation POC</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" />
   </p>
   <p>
     <label for="cemail">E-Mail</label>
     <em>*</em><input id="cemail" name="email"size="25"  />
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

我正在尝试使用jquery 验证进行表单验证 我正在尝试给出自己的错误消息。 但是此代码未运行。

当我尝试

 <input type="text" id="cemail" class="required"></input>

代码可以正常工作,但是使用此命令,我无法提供自定义错误消息。 如果我在上层代码中做错了什么,请告诉我。
编辑:我也有另一个问题,如果任何控件的验证失败,我想更改该控件的背景色。 而且我也想删除默认错误消息。

cemail和cname应该作为类而不是ID添加到输入元素。

例:

<input class="cemail" name="email" size="25"  />

格式应该是这样的...

$(document).ready(function() {
    $("#frm").validate({

        rules: {
            cname: {
                required: true
            },
            cemail: {
                required: true,
                email: true
            }
        },
        messages: {
            cname: { 
                required: "Please enter your name"
            },
            cemail: {
                email: "Email is not validated"
            }
        }
    });
});

cnamecemailinputname属性的值。

演示

有2个问题,主要是您需要使用name属性( 而不是 id属性),因此您的规则使用nameemail ,而不是cnamecemail 另外, email错误消息周围的{}需要删除。 总体而言,您希望如下所示:

$("#frm").validate({
    rules: {
        name: { required: true },
        email: { required: true, email: true }
    },
    messages: {
        name: "Please enter your name",
        email: "Email is not validated"
    }
});​

您可以在这里尝试一下

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM