问题
Still kind of new and I just started using bootstrap but basically when using stock HTML I see name attributes being used like so
<label for="email" class="label">E-mail Address</label>
<input name="email" type="text" id="email">
but with bootstrap there is typically no name attr used.
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Password</label>
<div class="col-lg-5">
<input type="password" class="form-control" id="inputPassword-" placeholder="Password">
</div>
</div>
I guess i'm just confused where the jquery validator is pulling information from. Does the email refer to the name attr or the label for?
rules: {
email: {
required: true,
email: true
},
回答1:
The validator uses the name attribute to find the field, as all form elements must have a name attribute.
The second block of HTML code you've posted is not valid for that reason.
回答2:
Adding this answer to clarify some ambiguous and misleading information posted within another's answer.
Quote Title:
"Do I need to use name attributes when validating a bootstrap form with jQuery Validation plugin?"
It does not matter what kind of form. When using the jQuery Validation plugin, any data input elements that are to be validated must each contain a unique name attribute, period... no workarounds, no exceptions. (The name attribute is the only way the jQuery Validation plugin can keep track of the data input elements being validated.)
This means that you cannot get around this requirement by using the .rules('add') method. I've seen this touted more than once on SO as a proposed workaround for elements without a name attribute. This will not work. No matter how rules are declared, the data input elements must still have a name attribute.
Demo without name attributes (broken validation): http://jsfiddle.net/L3u5n/
Identical demo, but with name attributes (working validation): http://jsfiddle.net/L3u5n/1/
See the "Markup recommendations" section of the "Reference docs" page.
"The
nameattribute is 'required' for input elements, the validation plugin doesn't work without it."
回答3:
name is must in the form element and you need it for jQuery validator too
you can also use
jQuery validator like this
.rules( “add”, rules )
$("el").rules("add", {
required: true,
email: true
});
来源:https://stackoverflow.com/questions/20140588/do-i-need-to-use-name-attributes-when-validating-a-bootstrap-form-with-jquery-va