使用Jquery进行表单验证

时间:2010-09-15 07:36:37

标签: javascript jquery validation visual-studio-2010

<!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 validation进行表单验证。我试图给出自己的错误消息。但是这段代码没有运行。

当我尝试

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

代码工作正常,但有了这个,我无法提供自定义错误消息。如果我在上面的代码中做错了,请告诉我。
编辑:我还有另外一个问题,如果任何控件的验证失败,我想更改该控件的背景颜色。我还想删除默认的错误消息。

3 个答案:

答案 0 :(得分:1)

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

示例:

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

答案 1 :(得分:1)

格式应该是这样的......

$(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"
            }
        }
    });
});

cnamecemailname的{​​{1}}属性值。

demo

答案 2 :(得分:1)

有两个问题,主要是您需要使用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"
    }
});​

You can give it a try here

相关问题