http://jsfiddle.net/sK9tL/1/
When I manually add the rule()'s in the console on my form page, it appears to validate as expected.
I'm not sure if there is something wrong with the way I am formatting this?
$('#freeFormAdd').validate({
rules:{
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
}
});
Then I use the .valid() to determine if the form is ready to submit. Since the page is "seamless" I don't need the form to submit, just to add some items to a cart (which is commented out in the jsfiddle).
Any advice?
Your form elements should have name attribute not id attribute, validator selects the elements based on their name attributes. Also instead of listening to the click event, you can use the submitHandler method:
$('#freeFormAdd').validate({
rules: {
freeFormName: {
required: true,
},
freeFormPrice: {
required: true,
},
freeFormQty: {
required: true,
}
},
submitHandler: function () {
alert('the form is valid');
}
});
Please note that I have moved the button to the form element's context so it triggers the submit event.
http://jsfiddle.net/QU3XM/
Related
I want to validate a form using jQuery validate and then inside submitHandler() I want to do some stuff. But it always refreshes the page even after using event.preventDefault(). Here is my code
$('form').validate({
rules: {
brand: {
required: true
},
model: {
required: true
},
description: {
required: true,
minlength: 15
},
name: {
required: true,
minlength: 2
}
},
messages: {
},
submitHandler: {
function (form) {
form.submit( e => {
e.preventDefault();
console.log("Hello...");
})
}
}
})
How to do it?
I orginally thought you had a syntax error that breaks the plugin....
submitHandler: {
function (form) {
....
}
}
Because it normally looks like this...
submitHandler: function(form) {
....
}
However, that idea is wrong... both formats work the same.
Secondly, you would never put a event.preventDefault() inside of the submitHandler callback...
it's not even recognized here because there is no default event to prevent.
the plugin is already automatically blocking the form's default submit event.
Finally, when using the submitHandler to run custom code, don't forget to include the default code for submitting the form as the last line in the function...
submitHandler: function(form) {
// your code here
console.log("Hello...");
form.submit(); // default form submit
}
Anyway, unless you fix the question by showing a demo, it's all working fine here...
DEMO: jsfiddle.net/e8xkwfzc
submitHandler: function(form){
alert("ok")
return false
}
add return false solves the problem
If always refresh the page after you click the submit button, when the best way disable submit event on the form.
<form method="post" action="/etc.php" onsubmit="return false;">
<input type="text" value="apple">
<input type="submit" value="Submit">
</form>
I have added form validation via class using Jquery.
However, when i use the addClass it seems to fail. Any Ideas?
$("label.choice3").click(function(){
$(".option").addClass("valueRequired");
});
$("#feedback_form").validate({
errorClass: 'feedback_form_error grid__item'
});
$('.valueRequired').each(function() {
$(this).rules('add', {
required: true,
messages: {
required: "Please select an option"
}
});
});
the class 'option' exists. I need to
<%= radio_button_tag "feedback[#{line_item['id']}][size_feedback]", "0", false, class: "option" %>
Onclick the following code is done.
$("label.choice3").click(function(){
$(".option").addClass("valueRequired");
});
This does add in the class of "valueRequired" which is fine.
But its the validation that does not seem to run once the class is added.
Without seeing your markup, I guess you run this piece:
$('.valueRequired').each(function() {
$(this).rules('add', {
required: true,
messages: {
required: "Please select an option"
}
});
});
against an empty selection? At the moment you run $('.valueRequired').each() do even any elements with that class exist in your code?
I have the following form that I am trying to add jquery validate to it. My issue is that none of the validation messages are appearing when I hit submit and if I hit submit twice, the form submits. So, essentially the validation is not working.
Does anyone see what I am doing wrong?
I am using the following libraries:
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form method="POST" action="" id="proposal-form">
<div class="panel-input"><input type="text" id="proposal-name" class="proposal-input" placeholder="Name *"></div>
<div class="panel-input"><input type="email" id="proposal-email" class="proposal-input" placeholder="Email *"></div>
<div class="panel-input"><input type="tel" id="proposal-phone" class="proposal-input" placeholder="Phone *"></div>
<div class="panel-input"><input type="text" id="proposal-location" class="proposal-input" placeholder="Location *"></div>
<input type="submit" value="SUBMIT" id="panel-submit">
</form>
$("#proposal-form").submit(function (e) {
e.preventDefault();
$("#proposal-form").validate({
onfocusout : true,
errorPlacement: function(error, element) {
error.appendTo( element.parent("input").next("input") );
},
rules: {
proposal_name: {
required: true,
minlength: 2
},
proposal_email: {
required: true,
email: true
},
proposal_phone: {
required: true,
digits: true,
minlength: 10
},
proposal_location: {
required: true,
minlength: 2
}
},
messages: {
proposal_name: {
required: "Please enter your name",
minlength: "Your name seems a bit short."
},
proposal_email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
},
proposal_phone: {
required: "Please enter your phone number",
digits: "Please enter a valid phone number",
minlength: "Your number seems a bit short."
},
proposal_location: {
required: "Please enter your name",
minlength: "Your name seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
var proposal_name = $('#proposal-name').val();
var proposal_email = $('#proposal-email').val();
var proposal_phone = $('#proposal-phone').val();
var proposal_location = $('#proposal-location').val();
$.ajax({
url: "php/proposal-send.php",
type: "POST",
data: {
"proposal_name": proposal_name,
"proposal_email": proposal_email,
"proposal_phone": proposal_phone,
"proposal_location": proposal_location
},
success: function (data) {
if (data == "Error!") {
alert(data);
} else {
$("#proposal-form")[0].reset();
$('#proposal-panel-inner').hide();
$('#proposal-success').fadeIn();
function successProposal() {
$('#proposal-panel').removeClass('active');
$('html').removeClass('is-navOpen');
$('.ssm-overlay').fadeOut();
}
setTimeout (successProposal, 2000)
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
}
});
}
});
});
Does anyone see what I am doing wrong?
The markup in your OP's code does not contain name attributes. Without name attributes, the validation will not work at all. See documentation. Not only must you have name attributes, only these names can be used within the rules object of .validate().
rules: {
proposal_name: { // <- this MUST match the NAME attribute only
required: true,
minlength: 2
}
....
Another major problem here is that the .validate() method is enclosed in a .submit() handler. Since the .validate() method is simply the plugin's initialization, AND the submit event is already captured and handled internally, you do not need your own .submit() event handler. (This is exactly why two clicks are needed). EDIT: A click handler is not much different. It's not needed and makes no sense (emphasis on "initialization", as in .validate() is the initialization method).
$("#proposal-form").submit(function (e) { // <- NOT needed
e.preventDefault(); // <- NOT needed
$("#proposal-form").validate({
onfocusout: true, // <- 'true' is NOT valid
....
You also do not need onfocusout: true because true is not an acceptable parameter for this option. The default behavior is to trigger validation on focus out, so setting onfocusout to true will break this plugin. It can only be set to false or an over-riding function.
$(document).ready(function() { // ensure DOM is ready
$("#proposal-form").validate({ // initialize plugin
// rules & options
....
Finally, the jQuery DOM traversal employed by your errorPlacement function does not seem to make any sense based on the posted markup.
element.parent("input").next("input")
There is no input next to the parent of the input. The parent of the input is a div and the next element is a div. The next input is inside of this div that is next to the parent. It also makes no sense why you'd want to place the error message on the following input element, especially for the last element, which would never display a message.
DEMO: jsfiddle.net/Lhouzn84/
Edit : Validation rules and message will match with name of the input element.
Please provide the name of your input control same as specified in Validation rules.
I'm trying to validate fields loaded using jQuery $().load();.
with jquery validation plugin (jqueryvalidation.org)
My code is:
var contactForm = $('#contact-form');
contactForm.validate({
rules: {
name: {
required: true,
},
email: {
required: true,
email: true
},
phone: {
required: false,
phoneUS: true
},
message: {
required: true
}
}
});
Unfortunately it doesn't work with elements loaded with load();
After some google searching I found some solution but they all are aimed on "events", not to pass dynamically added input to variable:
$(document).on('click','#submit',function() {});
I also tried to approach it with this code bellow :
$('.home').click(function() {
$("#article").load("./ #article > *",function(){
contactForm = $(this).find("#contact-form");
});
Also doesn't work though :(
I will appreciate any clues and help.
Try to add them dynamically :
$("#contact-form").find('input').each(function () {
$(this).rules("add", {
required: true
});
});
Hope this helps.
SOLVED: $.extend() twice in a row simply overwrites the previous object because objects are passed by reference. My fix was to do this:
var updateUserObj = $.extend({}, validationPluginDefaults);
var newUserObj = $.extend({}, validationPluginDefaults);
Then the validators are executed like this:
var whateverValidator = $.extend(updateUserObj,{new rules})
Update: Further research shows that what I'm trying to do appears to be correct but the problem may be in the object I am extending - "validationPluginDefaults"). Here it is below:
var validationPluginDefaults = {
ignore: [],
errorElement: 'p', //default input error message container <p>
errorClass: 'text-error', // default input error message class
focusInvalid: true, //focus on the first invalid field
messages: {},
invalidHandler: function (event, validator) { //display error alert on form submit
},
highlight: function (el) { // hightlight error inputs
//jQuery(el).closest('.control-group').addClass('error'); // set error class to the control group
},
success: function (err, el) {
jQuery(el).next(".text-error").hide();
jQuery(el).next(".text-error").remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onfocusin: function () {},
onfocusout: function () {}
};
From my testing it appears that even though I have two separate forms on a JSP page and each has different validation that I can still only use one jQuery Validate Plugin instance per page; is this correct?
Here's my code:
// Define validation rules for form one
var formOneValidator = $.extend(validationPluginDefaults,{
rules: {
firstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
lastName: {
minlength: 2,
required: true,
},
email: {
required: true,
email: true
}
}
});
var formTwoValidator = $.extend(validationPluginDefaults,{
rules: {
newFirstName: {
minlength: 2,
onlyAlphaAndHyphen: true,
required: true,
},
newLastName: {
minlength: 2,
required: true,
},
newEmail: {
required: true,
email: true,
}
}
});
$("#formOne").validate(formOneValidator);
$("#formTwo").validate(formTwoValidator);
What happens here is that formOne validator takes on all the rules of formTwoValidator after this code executes.
Is the solution to have only one validator and swap out rules depending on which form I'm in? It just seems strange that I wouldn't be able to define separate validators for each form on the page. Am I fundamentally misunderstanding something here?
you could use knockout and give each page a different view model which handles the different validation. That is how i would do it but i'm sure there will be a better answer.