I have next jquery code:
$("input").rules("add", {
required: true,
messages: {
required: 'Please enter your telephone number'
},
errorPlacement: function(error, element) {
console.log('bob');
element.insertBefore(error);
}
});
I am trying to add new rule like in answer in this question : jquery validation & id's ft numbers
I have such html code:
<form method='post' action='' id='#countersForm'>
<input id="88" class="counter_input active" type="text" enabled="">
<input id="89" class="counter_input active" type="text" enabled="">
</form>
My problems are:
1) Why browser tries to validate field on page loaded? I don't need this (message bob appeaing on page load.
2) Why only first input field is validating? I want to validate all fields.
3) Why console says , that element is not defined?
documentation says that element parameter contain validated element. console.log(element) says that it is undefiened. Why?
From documentation:
Read, add and remove rules for an element.
it says 'an' element. $('input') in your case returns two elements.
validation plugin uses name attribute of elements, your element's doesn't have names.
You have to initialize the plugin using validate() method on the form you want to validate, for e.g.
$("#myform").validate({ //where my form is the id of your form
rules: {
name: "required", //name is the name of your element
},
messages: {
}
});
Thanks for your answers and comments.
I solved my problem. Working code (current problem is solved) is here: http://jsfiddle.net/2LRv7/2/
There was a huge mistake in my js code. I put errorPlacement section to the rules function. I have to put this option to .validate section.
$("#countersForm").validate({
errorPlacement: function (error, element) {
console.log(error);
var br = $( "<br>" );
error.insertAfter(element);
br.insertAfter(element);
}
});
Also, as #TilwinJoy said, I used $('input').rules(/*....*/) wrong. I had to use each function.
This code is okay:
$("input").each(function () { // next code will affect all input fields
$(this).rules("add", { // $(this) is my input field
required: true,
digits: true,
messages: {
required: 'Это поле обязательно для заполнения',
digits: 'В поле могут быть только цифры'
}
});
});
Current problem solved, but I have another. If you want to help check this question: Class is not being added to the error element on first check , but when field is being checked again all going ok (jquery validation plugin)
Related
I have a multi step form with dynamically generated fields that I need to validate using jQuery, this is the form . How I can achieve this ?
// next step
$('.form-horizontal .btn-next').on('click', function() {
$("#multiphase").validate();
$('input[type="text"]').each(function(){
$(this).rule('add', {
required: true,
messages:{
required: "This field is required"
}
})
})
});
First of all, you can validate elements using "name" attribute. you can show below example:
<script type="text/javascript">
$("#pseudoForm").validate({
onfocusout:true,
rules:{
first_name:"required",
last_name:"required"
}
});
</script>
<!-- whatever -->
<div id="pseudoForm">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
</div>
also you can see reference as this link LINK
You should map the input fields to an object containing the rules for the validation plugin. I assume you're using this: http://jqueryvalidation.org/
Here's the general idea:
var fields = {};
$('form').find(':input').each(function() {
fields[this.name] = "required";
});
$('form').validate({
rules: fields
});
Of course you have to configure the plugin a bit more, but this is how you will handle the dynamic fields at least. An alternative would be to generate the rules server-side.
Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.
I use:
https://github.com/RobinHerbots/jquery.inputmask
https://github.com/1000hz/bootstrap-validator
(which uses jQuery native validation in this case)
Some strange behaviors:
Inputs with attribute required are validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)
When i write something into input field and then erase it, I get required error message
Can anyone give me some hint?
EDIT:
Relevant code:
HTML/PHP:
<form enctype="multipart/form-data" method="post" id="feedback">
<div class="kontakt-form-row form-group">
<div class="kontakt-form">
<label for="phone" class="element">
phone<span class="required">*</span>
</label>
</div>
<div class="kontakt-form">
<div class="element">
<input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php">
</div>
</div>
<div class="help-block with-errors"></div>
</div>
</form>
JS:
$(document).ready(function() {
$('#phone').inputmask("+48 999 999 999");
$('#feedback').validator();
});
I managed to use the RobinHerbots's Inputmask (3.3.11), with jQuery Validate, by activating clearIncomplete. See Input mask documentation dedicated section:
Clear the incomplete input on blur
$(document).ready(function(){
$("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});
Personnaly, when possible, I prefer setting this by HTML data attribute:
data-inputmask-clearincomplete="true"
The drawback is: partial input is erased when focus is lost, but I can live with that. So maybe you too ...
Edit: if you need to add the mask validation to the rest of your jQuery Validate process, you can simulate a jQuery Validate error by doing the following:
// Get jQuery Validate validator currently attached
var validator = $form.data('validator');
// Get inputs violating masks
var $maskedInputList
= $(':input[data-inputmask-mask]:not([data-inputmask-mask=""])');
var $incompleteMaskedInputList
= $maskedInputList.filter(function() {
return !$(this).inputmask("isComplete");
});
if ($incompleteMaskedInputList.length > 0)
{
var errors = {};
$incompleteMaskedInputList.each(function () {
var $input = $(this);
var inputName = $input.prop('name');
errors[inputName]
= localize('IncompleteMaskedInput_Message');
});
// Display each mask violation error as jQuery Validate error
validator.showErrors(errors);
// Cancel submit if any such error
isAllInputmaskValid = false;
}
// jQuery Validate validation
var isAllInputValid = validator.form();
// Cancel submit if any of the two validation process fails
if (!isAllInputValid ||
!isAllInputmaskValid) {
return;
}
// Form submit
$form.submit();
It's not exactly the solution, but...
changing inputmask for some equivalent solves the problem.
Still far from perfect, though : (
EXPLANATION:
Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.
I used:
https://github.com/digitalBush/jquery.maskedinput
I have the same issue when combined these two libs together.
Actually there is a similar ticket here: https://github.com/RobinHerbots/Inputmask/issues/1034
Here is the solution provided by RobinHerbots:
$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});
The validator assumes that it is not empty when the mask focus/hover is there.
simply turn focus and hover of the mask off will fix the problem.
I solved this problem with:
phone_number: {
presence: {message: '^ Prosimy o podanie numeru telefonu'},
format: {
pattern: '(\\(?(\\+|00)?48\\)?)?[ -]?\\d{3}[ -]?\\d{3}[ -]?\\d{3}',
message: function (value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^ Nieprawidłowa wartość w polu Telefon");
}
},
length: {
minimum: 15,
message: '^ Prosimy o podanie numeru telefonu'
},
},
I have several forms on one page that differ based on the forms' IDs. The ID's differ by an appended _0, _1, _2 etc (an index value created by a rails each do loop).
I'm trying to validate these forms, however to keep my code DRY, I'd like the form selector to be dynamic. I need to somehow grab the form's ID value ("_0") and add it to the jQuery selector.
This Fiddle gives an exmaple of how I'm tackling the problem now.
The code inside of the validation() block is the same between the jQuery functions. I need to set the selector variable to something like this:
$("new_loan_question_answer_"+i)
I'm not sure how to pass the _0 or _1 form the HTML form to the jQuery function.
form html
<div class="form">
<p>Question #1 text</p>
<form id="question_response_0">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form id="question_response_1">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
jquery
$(function () {
$("#question_response_0").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
$(function () {
$("#question_response_1").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
Don't bother with incremental id attributes. It becomes a pain to maintain and leads to issues keeping code DRY. This kind of thing is exactly what classes were invented for:
<div class="form">
<p>Question #1 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
Now you only need to attach validate to the .question_response class. Unfortunately it seems that the error highlighting (and possibly other features) is bugged in the validate plugin when instantiating on a selector that contains multiple form elements, so you need to loop through each form in turn:
$(function () {
$('.question_response').each(function() {
$(this).validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
});
Example fiddle
Check out http://api.jquery.com/submit/ for example.
If you use an event handler to call a function, then the event may contain the information you need (ID of submitted form).
Information regarding the event object is available here: http://api.jquery.com/category/events/event-object/
Could use the classes shown already in your markup, or add a class to form tags:
$('div.form form').validate({/* options*/}) ;
This will include all forms that match the selector and each will have it's own validation instance
I am using Casperjs 1.1.0-beta3 and trying to fill a form by an 'id' selector. I have successfully have used "input[name='userID']" but using an 'id' as a selector always fails with an error similar to the below.
CasperError: Errors encountered while filling form: no field matching css selector "#header-my-account-userid" in form; no field matching css selector "#header-my-account-password" in form
Method 1 works fine. Method 2, 3, 4 all fail. I ONLY TRY ONE METHOD AT A TIME AND COMMENT THE OTHERS OUT. I also cut the extra form tags out for this question.
I found this stackoverflow question on the same subject it still doesn't work.
Any ideas?
HTML
<input id="header-my-account-userid" name="userID" class="m-my-account-userid" maxlength="80" autocomplete="off" placeholder="Email or Rewards #" type="text">
<input id="header-my-account-password" name="password" class="m-my-account-password" maxlength="20" autocomplete="off" placeholder="Password" type="password">
<button type="submit" name="submit" id="header-my-account-sign-in" class="analytics-click m-button-default" title="Sign In">Sign In</button>
Casperjs Script
casper.then(function() {
casper.waitForSelector('form[name=directLoginForm]', function() {
// Method 1 Works
this.fillSelectors("form[name=directLoginForm]", {
'input[name=userID]' : username,
'input[name=password]' : password
}, true);
// Method 2 Does not work
this.fillSelectors("form[name=directLoginForm]", {
'input[id="header-my-account-userid"]' : username,
'input[id="header-my-account-password"]' : password
}, true);
// Method 3 Does not work
this.fillSelectors("form[name=directLoginForm]", {
'header-my-account-userid' : username,
'header-my-account-password' : password
}, true);
// Method 4 Does not work
this.fillSelectors("form[name=directLoginForm]", {
'#header-my-account-userid' : username,
'#header-my-account-password' : password
}, true);
});
});
Well i tried, they all work (except 3 because your selector is invalid).
I put the bool to false to see the changes, but you shouldn't have 'Errors encountered while filling form: no field matching css selector "#header-my-account-userid'.
It's not a casper error so, it's specific to your case. It doesn't recognize your id for obscure reasons.
this.sendKeys('input[id="header-my-account-userid"]', username);
sendKeys works also.
Wait for the form to be loaded to fill the form using the selectors.Use have waitForSelector(),waitFor(),wait() etc other than waitForResource()
casper.start('your_url_here',function(){
this.echo(this.getTitle());
});
casper.waitForResource("your_url_here",function() {
this.fillSelectors('#loginform', {
'input[name="Email"]' : 'your_email',
'input[name="Passwd"]': 'your_password'
}, true);
});
A minimal example revealed that only method 3 shouldn't work. I suspect you check for 'working' form by checking if the next page loads. It might be the case that casper doesn't find the submit button. Try explicitly clicking the button.
Additionally, PhantomJS has sometimes a problem with non-quoted attribute selectors. You should change
"form[name=directLoginForm]"
to
"form[name='directLoginForm']"
I find that this happens when casperJS is too fast for the browser and a casper.wait() will solve the issue.
This is an example:
// Make a test order
casper.then(function() {
casper.waitForSelector('#onestepcheckout-form', function() {
this.fillSelectors('#onestepcheckout-form', {
'input[id="billing:telephone"]': '12344534',
'input[id="billing:postcode"]': '432323',
'input[id="billing:city"]': 'London',
'input[id="billing:street1"]': 'Lambada is a good music'
}, false);
})
casper.wait(5000, function() {
this.fillSelectors('#onestepcheckout-form', {
'#sagepaydirectpro_cc_owner': 'Fizipit o Moyazoci',
'input[id="agreement-1"]': true
}, true);
})
this.test.pass('form populated');
});
I have a form which is being validated using Jquery Validate.The form contains 2 checkboxes with the same name, of which at least one has to be selected. To accomplish this, i am using the .validate() on the checkboxes name , along with the rule :required".
While i am able to validate successfully, (i.e error messages pop up when no checkboxes are selected), the error messages are being displayed after the first checkbox, which disrupsts my formatting.
I am currently using errorElement and errorPlacement to make the error messages show up in a pair of span tags after each input element, but it seems to be not applying to the checkboxes.
HTML(Extract) :
<form id='BizAddItem' name='BizAddItem' method='post' action='additemprocess.php' enctype='multipart/form-data' novalidate='novalidate'>
//More input elements above
<div class='BizAddItemDetails'>
<label for='BizFulfilment'>Order Fulfilment:</label>
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>Delivery  
<input type='checkbox' id='BizFulfilment' name='BizFulfilment[]'>In-Store Pickup
<span></span>
</div>
//More input elements below
</form>
jQuery code (Extract):
$('#BizAddItem').validate({
errorElement:"span",
errorPlacement:function(error,element){
error.insertAfter(element);
},
rules:{
//More items above
'BizFulfilment[]':{
required:true
},
},
messages:{
//More items above
'BizFulfilment[]':{
required:"Please select at least one option"
},
},
submitHandler:function(form){
form.submit();
}
})
Any help rendered would be appreciated. Thanks!
Try this....
errorPlacement:function(error, element)
{
if($(element).attr("name")=="BizFulfilment[]")
{
$(element).parent().append(error);
}else
{
$(error).insertAfter(element);
}
},