Jquery验证,将错误消息放在现有元素中,而不是生成<label>标记</label>

时间:2013-06-10 17:23:21

标签: jquery jquery-validate

我使用Jquery validation plug-in来验证下面的这两个输入元素。  当输入无效时,插件将在输入字段后面生成标签标记,例如:<label for="company" style="">Required !</label>

问题: 如何将错误消息放在现有的<span class="help-inline">中,而不是生成新的<label>

非常感谢您的帮助。

<script type="text/javascript">

 $('#signUpForm').validate({
                            debug: false,
                            rules: {company:"required",username:"required"},
                         messages: {company:"Required !",username:"Required !"}
                          })// End of validate()

</script>


<div class="control-group">
   <label class="control-label" for="company">Company Name</label>
   <div class="controls">
      <input type="text" name="company">
      <label for="company">Required !</label> // -> this line is generated by Plug-In.
      <span class="help-inline">(required)</span>
   </div>
</div>

<div class="control-group">
   <label class="control-label" for="username">User Name</label>
   <div class="controls">
      <input type="text" name="username">
      <span class="help-inline">(required)</span>
   </div>
</div>

1 个答案:

答案 0 :(得分:15)

利用内置选项并让插件创建span元素会更容易。生成的HTML的最终结果将是您要求的内容。

  • 使用errorElement<label>更改为<span>

  • 使用errorClass将默认错误类更改为help-inline

<强>的jQuery

$(document).ready(function () {

    $('#signUpForm').validate({ // initialize the plugin
        errorElement: 'span',
        errorClass: 'help-inline',
        rules: {
            company: "required",
            username: "required"
        },
        messages: {
            company: "Required !",
            username: "Required !"
        }
    });

});

<强> HTML

<form id="signUpForm">
    <div class="control-group">
        <label class="control-label" for="inputCompanyName">Company Name</label>
        <div class="controls">
            <input name="company" type="text" id="inputCompanyName" placeholder="" />
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="inputFirst">User Name</label>
        <div class="controls">
            <input name="username" type="text" id="username" placeholder="" />
        </div>
    </div>
    <input type="submit" />
</form>

DEMO:http://jsfiddle.net/eRZFp/

BTW :您的User Name字段缺少name属性name="username"。为使此插件正常工作,所有输入元素都必须包含唯一的name属性。