在自定义div上显示JQuery验证错误

时间:2013-02-02 16:24:42

标签: jquery jquery-validate

我有以下HTML表单:

<form method="post" action="register.php" class="form-horizontal" id="form-registrazione">
          <fieldset>
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                <h3 id="registrazioneLabel">Registrazione</h3>
              </div>
              <div class="modal-body">
                <div class="control-group">
                      <!-- Username -->
                      <label class="control-label">Username</label>
                      <div class="controls">
                        <div class="input-prepend">
                          <span class="add-on"><i class="icon-user"></i></span>
                          <input name="username" class="span2" placeholder="Leonardo" id="username" type="text">
                        </div>
                        <div id="username_msg"></div>
                      </div>

                    </div>



                <div class="control-group">
                      <!-- Email -->
                      <label class="control-label">Email</label>
                      <div class="controls">
                        <div class="input-prepend">
                          <span class="add-on"><i class="icon-envelope"></i></span>
                          <input name="email" class="span2" placeholder="mario@rossi.com" id="email" type="email">
                        </div>
                        <div id="email_msg"></div>
                      </div>
                    </div>

                <div class="control-group">
                      <!-- Password -->
                      <label class="control-label">Password</label>
                      <div class="controls">
                        <div class="input-prepend">
                          <span class="add-on"><i class="icon-key"></i></span>
                          <input name="password" class="span2" placeholder="Password" id="password" type="password">
                        </div>
                        <div id="password_msg"></div>
                      </div>
                    </div>

                <div class="control-group">
                  <!-- Conferma password -->
                  <label class="control-label">Conferma password</label>
                  <div class="controls">
                    <div class="input-prepend">
                      <span class="add-on"><i class="icon-key"></i></span>
                      <input name="repassword" class="span2" placeholder="Password" id="repassword" type="password">
                    </div>
                    <div id="repassword_msg"></div>
                  </div>
                </div>

              </div>
              <div class="modal-footer">
                <input type="submit" value="Registrati" class="btn btn-primary">
                <button class="btn" data-dismiss="modal" aria-hidden="true">Chiudi</button>
              </div>
        </fieldset>
      </form>

以下Javascript验证码:

<script>
    // SI ACCETTANO SOLO USERNAME CON CARATTERI ALFANUMERICI, SPAZI, TRATTINI E UDNERSCORE
    jQuery.validator.addMethod("alphanumeric", function(value, element) {
        var stringa = new String(value);
        stringa = stringa.replace(" ", "");
        stringa = stringa.replace("-", "");
        stringa = stringa.replace("_", "");
        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(stringa.valueOf());
    });

    // SCRIPT CHE CONVALIDA IL FORM DI REGISTRAZIONE
    $(document).ready(function(){
        $('#form-registrazione').validate({
        rules: {
          username: {
            minlength: 6,
            maxlength: 15,
            alphanumeric: true,
            // L'USERNAME NON DEVE ESSERE GIA' USATO
            remote: {
                url: "do_action.php?action=username_used",
                type: "post",
                async: false,
                data: {
                  email: function() {
                    return $("#username").val();
                  }
                }
            },
            required: true
          },
          email: {
            required: true,
            email: true,
            // L'EMAIL NON DEVE ESSERE GIA' UTILIZZATA
            remote: {
                url: "do_action.php?action=email_used",
                type: "post",
                async: false,
                data: {
                  username: function() {
                    return $("#email").val();
                  }
                }
            },
          },
          password: {
            minlength: 8,
            required: true
          },
          repassword: {
            minlength: 8,
            required: true,
            equalTo: "#password"
          }
        },
        messages: {
            username: {
                required: "Scegli il tuo nome utente.",
                minlength: "Inserisci almeno almeno 6 caratteri.",
                maxlength: "Inserisci meno di 15 caratteri.",
                alphanumeric: "Si accettano soltanto caratteri alfanumerici, spazi, trattini e underscore.",
                remote: "L'username &egrave; gi&agrave; utilizzato da un altro giocatore, per favore scegline un altro."
            },
            password: {
                required: "Imposta una password.",
                minlength: "La password deve essere lunga almeno 8 caratteri.",
            },
            repassword: {
                required: "Conferma la tua password.",
                minlength: "La password deve essere lunga almeno 8 caratteri.",
                equalTo: "Le due password non combaciano."
            },
            email: {
                required: "Inserisci un indirizzo email.",
                email: "L'indirizzo email inserito non &egrave; corretto.",
                remote: "L'email &egrave; gi&agrave; utilizzata da un altro giocatore, puoi utilizzare un'altra email oppure <a href='recover.php'>recuperare i dati del tuo account</a>."
            }
        },
        highlight: function(label) {
            $(label).closest('.control-group').removeClass("success").addClass('error');
        },
        success: function(label) {
            label
                .addClass('valid')
                .closest('.control-group').addClass('success');
        }
      });
    });
</script>

代码有效,它还会检查用户名/电子邮件是否已被使用。问题是,如果错误字符串太长,文本会离开页面(没有新行),所以我创建了四个div,我想在其中放置错误消息,以便文本在需要时创建新行。 / p>

我的目标是显示div“#username_msg”中的每个用户名错误,div中的每个电子邮件错误“#email_msg”等等。我尝试过很多东西,我搜索过谷歌,我也试过了showErrors方法但是我无法解决我的问题...所以我在这里。

我正在使用Twitter Bootstrap,表单正确显示在模态(http://twitter.github.com/bootstrap/javascript.html#modals)中。

提前致谢!

2 个答案:

答案 0 :(得分:2)

  

引用:“我的目标是显示div #username_msg中的每个用户名错误,   div #email_msg等中的每个电子邮件错误

您不能将每条消息都放在自己唯一标记的div中。但是,您可以将邮件放在div元素而不是label中。但是,这并不能简单地使用CSS格式化label元素来解决您的问题。

http://docs.jquery.com/Plugins/Validation/validate#toptions

  

errorElement ,字符串,默认值:“label”

     

使用此元素类型创建错误消息并查找   现有的错误消息。默认的“标签”具有优势   在错误消息和无效字段之间创建有意义的链接   使用for属性(总是使用,无论元素   类型)。

根据评论,使用div,因为OP希望消息在 <{1}}元素下显示

input

然后您可以使用CSS控制errorElement: "div" 的显示方式......

div

工作演示: http://jsfiddle.net/f9Ut4/1/


修改

解释 - 在您的div.error { width: 200px; // whatever you need white-space: normal; // to ensure wrapping despite twitter bootstrap css } 继承的Twitter Bootstrap CSS文件中有一条规则white-space: nowrap,该文件告诉其文本内容不包装。我上面建议的规则div.error只是反转了white-space: normal规则,因为它有一个更具体的目标,nowrap,它将采用优先级超过Twitter Bootstrap CSS中的规则。

答案 1 :(得分:0)

尝试给出打印错误的div的max-width。因此,如果错误字符串很大,它们会自动将它们包装成新行