JQuery Validation use different divs for different input elements for errors, and multiple error classes

StackOverflow https://stackoverflow.com/questions/22162205

Pergunta

I'm using JQuery Validation on my form, and I'm trying to get the input elements to show a red border if the input is invalid, and also show the error message underneath the appropriate input element.

My HTML code is basically this:

<div id="formContainer">
<form id="mainForm" action="action.php" method="post">
    <input class="formTextBox" type="url" name="website" placeholder="website" required />
    <input class="formTextBox" type="email" name="email" placeholder="e-mail" required />
    <button type="submit" class="buttonForm" id="submitBtn"> <span id="buttonContent">Snapshot my site</span> </button>
</form>
</div>

I've tried adding specific DIVs after the form (still in #formContainer), that will get populated with the error using the errorPlacement option. Inside the function I check the element's name attribute, and append the error to its corresponding div... but when I continue typing, or clicking between inputs, the error message keeps repeating and repeating and no error ever gets cleared (I see the same error message many times, one underneath the other).

I've tried putting each input element inside its own div (with a fixed width), and set the errorElement to DIV, so when JQuery Validation creates that new div and appends it next to the input element, it will get pushed underneath... but that caused some design issues, and I'd prefer the 2 error containers to be in the #formContainer div (and it seems a little bit wonky to do it that way).

Also, what do I do if need to style both the error on the input element, and the error message DIVs?

Here's a little illustration of what I had in mind: enter image description here

Thanks!

Foi útil?

Solução

Try

<div id="formContainer">
    <form id="mainForm" action="action.php" method="post" novalidate>
        <div class="input-control">
            <input class="formTextBox" type="url" name="website" placeholder="website" required />
        </div>
        <div class="input-control">
            <input class="formTextBox" type="email" name="email" placeholder="e-mail" required />
        </div>
        <button type="submit" class="buttonForm" id="submitBtn"> <span id="buttonContent">Submit</span> 
        </button>
    </form>
</div>

then

#formContainer {
    vertical-align: top;
}
.input-control {
    display: inline-block;
    vertical-align: top;
}
div.error {
    display: block;
    background-color: red;
    color: white;
}
input.error {
    border: 1px solid red;
}
.formTextBox {
    width: 210px;
    background-color: white;
    color: black;
}

and

jQuery(function ($) {
    var validator = $('#mainForm').validate({
        rules: {},
        messages: {},
        errorElement: "div"
    });
});

Demo: Fiddle

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top