xuT
xuT

Reputation: 318

Display JQuery Validation errors on custom divs

I have the following HTML form:

<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="[email protected]" 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>

And the following Javascript Validation code:

<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>

The code works, it also checks if username/email are already used. The problem is that if the error string is too long the text goes out of the page (no new lines), so I created four divs in which I would like to place the error messages so the text will make new lines when needed.

My goal is to display every username error in the div "#username_msg", every email error in the div "#email_msg", etc. I tried many things, I searched and Google, I also tried the showErrors method but I couldn't fix my problem... so here I am.

I am using Twitter Bootstrap and the form is displayed correctly into a Modal (http://twitter.github.com/bootstrap/javascript.html#modals).

Thanks in advance!

Upvotes: 1

Views: 9252

Answers (2)

Sparky
Sparky

Reputation: 98738

Quote: "My goal is to display every username error in the div #username_msg, every email error in the div #email_msg, etc.

You cannot put each individual message within their own uniquely tagged div. You can, however, put the messages inside of a div element instead of a label. However, this will not solve your issue any better than simply using CSS to format the label element.

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

errorElement, String, Default: "label"

Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type).

As per comments, using div since the OP wants the message to display under the input element.

errorElement: "div"

Then you can control how the div displays using CSS...

div.error {
    width: 200px; // whatever you need
    white-space: normal;  // to ensure wrapping despite twitter bootstrap css
}

Working Demo: http://jsfiddle.net/f9Ut4/1/


EDIT:

Explanation - there was a rule, white-space: nowrap, within the Twitter Bootstrap CSS file that was inherited by your div.error which told its text content to not wrap. The rule I suggest above, white-space: normal, simply reverses the nowrap rule and since it has a more specific target, div.error, it will take precedence over the rule within the Twitter Bootstrap CSS.

Upvotes: 2

asifsid88
asifsid88

Reputation: 4701

Try giving max-width to your div which prints error. So if the error string is huge they will automatically wrap them into new line

Upvotes: 0

Related Questions