2010-09-15 95 views
0
<!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进行表单验证。我试图给我自己的错误消息。但是这段代码没有运行。使用jquery进行表单验证

当我试图

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

代码工作正常,但与此,我不能给自定义错误消息。请让我知道如果我在上面的代码中做错了什么。
编辑:我还有一个问题,如果验证失败的任何控制,我想改变该控件的背景颜色。我也想删除默认的错误信息。

回答

1

有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" 
    } 
});​ 

You can give it a try here

1

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

例如:

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

@Maris无法正常工作。 – 2010-09-15 07:48:28

+0

但是,如果我使用名称=“cemail”......它的工作。 – 2010-09-15 07:54:38

+0

好的,对,我很接近:) – 2010-09-15 08:01:48

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

cnamecemailinputname属性的值。

demo