jQuery validation - Display error message for each field - javascript

http://jsfiddle.net/nXqd/qC2Ya/6/
Take a look at the jsfiddle. When I enter wrong data in two inputs and clicking submit, I only receive the error message on the first one. Now I want two of them which have the name attribute in the form displayed as well.
In this example, I use the same name on purpose to get these values on the backend easier. I just loop through the list and get all information.

You are doing it wrong. You have added same name for both fields. Same name attributes are used to combine the fields in a group. You have to use class based validation.

working demo http://jsfiddle.net/xr5g6/1/
Hope it fits your needs. :)
code
$("form").validate({
rules: {
number: {required: true, range: [1,2]},
number2: {required: true, range: [1,2]}
}
});
​html
<form name="myForm">
<fieldset>
<legend>My Form</legend>
<label for='number'>Number</label>
<input name='number'class='required'/> <br />
<label for='number'>Number</label>
<input name='number2' class='required'/>
<label for='change-range'>Max range</label>
<input name='change-range' class='required'/>
</fieldset>
<input type="submit">
</form>
​

You should use different name attriburtes for different inputs.
Demo: http://jsfiddle.net/xYTNw/

Related

Jquery validate require from group not working

Having some trouble with this function of the validation plugin:
http://jqueryvalidation.org/require_from_group-method
Related part of the form:
<input class="org-group" type="checkbox" name="org[1]" id="org[1]" value="on">
<input class="org-group" type="checkbox" name="org[2]" id="org[2]" value="on">
<input class="org-group" type="checkbox" name="org[3]" id="org[3]" value="on">
This list of checkboxes is dynamic. It could have 2 entries, or 50 entries, that's why I am using an array in the form. I want the plugin to ensure that one of the xxx checkboxes in the org-group class is checked.
I use this in the plugin:
$( "#orgform" ).validate({
rules: {
org[]: {
require_from_group: [1, ".org-group"]
},
However, it's not working. The form just submits regardless the amount of boxes checked. The "submithandler" works fine. I have some other text fields in this form which are required. If these fields are not filled, the validation runs fine.
What am I doing wrong?
You need to make sure you've referenced all of the required JQuery libraries. If you're using just the core library, validation won't work.
Make sure you're also referencing additional-methods.min.js
Fiddle Example
Once you have all of the required references, you'll need to modify your html content, so that all of your check boxes have the same name. Validation won't work if all of the names are unique. The ids will obviously have to remain unique.
Updated Html:
<form id="orgform">
<input class="org-group" type="checkbox" name="org" id="org[1]" value="on">
<input class="org-group" type="checkbox" name="org" id="org[2]" value="on">
<input class="org-group" type="checkbox" name="org" id="org[3]" value="on">
<input class="org-group" type="checkbox" name="org" id="org[4]" value="on">
<input type="submit" value="Validate">
</form>
Notice that all of the checkboxes have a name of "org".
After you've updated your html, update the call to validate to reference "org" instead of "org[]". If you inspect the console you'll notice the following error:
Uncaught SyntaxError: Unexpected token [
This is because the rules property doesn't accept [ or ]
With the html changes, you'll also need to update your JQuery.
Updated JQuery:
$("#orgform").validate({
rules: {
org: {
require_from_group: [1, ".org-group"]
}
}
});
Note: Please see the Fiddle example I've linked above for a working example.

AngularJS form validatation of auto-generated form

I am trying to validate an auto-generated form (via AngularJS v1.3) which inputs' names are in format:
form_name[field_name]
The very basic example would be:
<form name="morgageCalculator">
<input type="text" class="form-control"
name="morgageCalculator[homeValue]" value="0"
data-ng-model="data.homeValue" required="required"/>
</form>
As you can see, the input name is morgageCalculator[homeValue]. Now I would like to add an error message below it:
<div class="error"
data-ng-show="!morgageCalculator.morgageCalculator[homeValue].$pristine && morgageCalculator.morgageCalculator[homeValue].$invalid">
Please enter a number
</div>
For very obvious syntax reasons this expression is not valid:
morgageCalculator.morgageCalculator[homeValue].$pristine
But this one also does not work:
morgageCalculator["morgageCalculator[homeValue]"].$pristine
So, the question, is there any sane way of accessing those fields? I wouldn't mind moving the validation to some controller function, but I was faced with same issue of inability to access field object.
Any help/hint would be greatly appreciated.
With help of #dfsq from comment section, I was able to find the error. Unlike my SO question, my code was missing data-ng-model.
Validation will not fire at all if input was not bound to model....
The correct snippet:
<form name="morgageCalculator">
<input type="text" class="form-control"
name="morgageCalculator[homeValue]" value="0"
data-ng-model="data.homeValue" required="required"/>
<div class="error"
data-ng-show="!morgageCalculator['morgageCalculator[homeValue]'].$pristine && morgageCalculator['morgageCalculator[homeValue]'].$invalid">
Please enter a number
</div>
</form>

How to set an HTML5 input to required via JavaScript

I have a form with many input fields and radio buttons.
Some fields must get the required - attribute. But which fields are required depends on which radio button has clicked.
(If "Company-email" is checked -> input field "Company email" is required, otherwise private email)
Initially all field should be required=false.
But that does not work. No matter which value I give to the required-attribute, required is always true.
So... how can I set an input-field initially to required=false?
EDIT:
Thank you all for your answers.
In fact nothing works.
I made a test html document like this:
function test2()
{
document.getElementById("33").attr("required");
}
<form method="post" action="#">
<input type="text" id="33">
<input type="text">
<input type="text">
<input type="text">
<input type="radio" onclick="test2()">
<input type="submit" value="send">
</form>
It's unbelievable but this very simple example does not work.
The field with id 33 is not a required-field.
I can submit the form and nothing is checked.
What is wrong here?
EDIT 2:
Now I found the solution:
function test2()
{
document.getElementById("33").required = true;
}
This works for me on my example page. I have to check if i really can work with that in my real project.
required is a boolean attribute, so no matter what value you give it will still be required.
Instead of setting attributes you can set the element property
document.getElementById('companyemail').required = false;
Remove the required attribute from the fields that are not required.
In HTML5, this is an example of how to use required:
<input type="text" name="name" required>
So chances are that even when setting it to false (or anything, in fact) would be considered true.
$(document).ready(function() {
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
$("#companyemail").attr("required");
$("#privateemail").removeAttr("required");
}
else{
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
}
});
});
I hope this may help, let me know your feedback...
try to remove the required attributes
your-input.removeAttr( "required" );

How to validate three separate fields as a date

I am trying to validate a date that is separated into three fields (year, month, and day, of course). I cannot change these fields, as much as I'd like to. I am using the jQuery Validation plugin (also not by my choice). I cannot figure how to validate all three fields as one. Even validating them individually would suffice.
My HTML is as follows.
<div class="date-field requiredField">
<div class="date-picker hasDatepicker" id="dp1412187717156" style="display: none;">...</div>
<input type="text" class="month" required="required" maxlength="2" placeholder="MM" title="Month" value="1">
/
<input type="text" class="day" required="required" maxlength="2" placeholder="DD" title="Day" value="1">
/
<input type="text" class="year" required="required" placeholder="YYYY" title="Year" value="1973">
<span class="date-pick-button"></span>
<span class="date-clear-button"></span>
</div>
I am invoking the validator as follows:
$("#SignUp_Enrollment").validate({
focusInvalid : false,
rules: {
co_ssn: {
ssn: true
},
first_name: {
required: true
},
last_name: {
required: true
}
// some more rules
},
invalidHandler: function (form, validator) {
// style the invalid fields
},
submitHandler: function (form) {
form.submit();
}
});
I am of course validating other fields, but this plugin is not showing me any mercy. I've tried adding month, day, and year rules to no avail. Any suggestions on what direction to take?
Quote OP:
"Even validating them individually would suffice."
Your code is broken because none of the fields in your HTML markup contain a name attribute. A unique name is mandatory in order for this plugin to operate. It's how it keeps track of the input elements.
See: http://jqueryvalidation.org/reference/#markup-recommendations
It's not shown in your markup, but all relevant input elements must also be contained within <form></form> tags. This plugin will not work otherwise.
Since you already have the date saved into an hidden field, you can also just validate the hidden field.
<input type="hidden" name="myDate" />
Activate validation on hidden fields by using the ignore: [] option.
Then as long as this hidden field has a unique name attribute, you can apply validation rules the same as you would on any other field.
Use the errorPlacement callback to precisely place the message attached to the hidden field.
You can merge this three fields to one (hidden input), and validate this input
var day, month, year;
day = $('.day').val();
month = $('.month').val();
year = $('.year').val();
$('.hidden-date-input').val([day, year, month].join('-'));

form validations drop ng-model objects?

Say I have the following form:
<form>
<input type="text" required ng-model='myValue' ng-maxlength='5'></input>
{{myValue}}
{{myValue.length}}
</form>
When the length of the text in the input exceeds the maxlength, the model becomes empty. Is there any way to prevent this behaviour while applying this validation, without rolling a custom form level validator?
at first, input element no end mark(</input), the correct like this:<input name="test" type="text"/>
you can handle form.test.$error.maxlength to deal something, example code:
<form name="form">
<input name="name" type="text" required ng-model='myValue' ng-maxlength='5'/>
<div>value:{{myValue}}</div>
<div>length:{{myValue.length}}</div>
<div>validate:{{form.name.$error.maxlength}}</div>
</form>
According your means, the invalid value lead to null model, I think this is no problem.

Categories