Prevent form from submitting jQuery [duplicate] - javascript

This question already has answers here:
jquery validation: prevent form submit
(4 answers)
Closed 2 years ago.
In my form, the user has to enter 4 values to generate the multiplication table.
To validate the user's input I use jQuery. If the input is not valid (blank, non-integer number, etc) then the error message is displayed. The "Submit" button should only work when the input is valid.
I used this to prevent the form from submitting (source: Preventing a form from submitting in jQuery Validate plugin's submitHandler function):
$("#inputForm").submit(function(generateTable) {
generateTable.preventDefault();
}).validate({
//code
});
Here is the validate.js file:
function generateTable() {
//code
return false;
}
$(function() {
$("#inputForm").submit(function(e) {
e.preventDefault();
}).validate({
//rules
//messages
});
Here is HTML file:
<form id="inputForm" class = 'card p-3 bg-light' class="form-horizontal" onsubmit="return generateTable();">
The issue is that the form is getting submitted even if the input is not valid. How can I prevent the form from being submitted?

You don't need to call the submit function, just use as following.
$("#inputForm").validate({
rules: {
"name": {
required: true,
minlength: 5
},
"email": {
required: true,
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
See this fiddle here

Related

How to customize submitHandler() in jQuery validation?

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>

jquery choosen select validation messages are not dis-appering untill the form submit

jQuery chosen select validation messages are not disappearing until the form submit. I applied required validation if I submit the form without choosing the value error message is displaying. But after I choose it is not disappearing as normal select boxes, it is staying until the form submit.
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" });
$("#postJob").validate({
rules: {
skills:{
required:true,
},
});
please provide a running code snippets to understand the problem more easily.
jQuery validate messages are disappeared once the validation is fulfilled.
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5
},
"email": {
required: true,
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
Here is the fiddle:
http://jsfiddle.net/amwmedia/sw87W/

Jquery Validate allowing submit with rules not met

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.

Jquery validation not working second time

The problem is this jquery validation is not working in my form second time. Its working first time perfectly but second time its shows error message but form is going to submit. The code is here
(function ($, W, D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function () {
//form validation rules
$("#aspnetForm").validate({
rules: {
firstname: "required",
lastname: "required",
company: "required",
jobtitle: {
required: true,
},
phone: {
required: true,
number: true
},
email: {
required: true,
email: true
},
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
company: "Please enter your company name",
jobtitle: "Please enter your job title",
phone: "Please enter a valid phone number",
email: "Please enter a valid email address",
},
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
//form.submit(function (e) {
// e.preventDefault();
// if (flag) {
// createListItem();
// }
//});
}
});
}
}
//when the dom has loaded setup form validation rules
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
$('#newsletterModal').on('hidden.bs.modal', '.modal', function () {
clearFields();
});
$('#newsletterModal').on('shown.bs.modal', function (e) {
$('#lblMsg').empty();
});
});
})(jQuery, window, document);
can any one help me
Your submitHandler callback function...
submitHandler: function (form) {
$('#aspnetForm').on('submit', function (e) {
e.preventDefault();
if (flag) {
createListItem();
}
});
}
Do not put a submit event handler inside of the submitHandler callback! It's unclear to me what you're trying to do but the submitHandler callback function of the plugin has already captured & replaced the default submit event of the form.
Also, whenever you declare your own submitHandler function, you are over-riding the default built into the plugin. Since I see nothing inside of your custom submitHandler that submits the form, the form will never be submitted.
You'll either need to remove the submitHandler to allow the form to be submitted (when valid) as per the default functionality OR you'll need to put $(form).submit() inside of it someplace.
submitHandler: function (form) {
if (flag) {
createListItem();
}
$(form).submit();
}
NOTE:
Wrapping up everything like this is superfluous, unnecessary, verbose, and arcane...
(function($,W,D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function() {
$("#aspnetForm").validate({ .... });
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
It serves no useful purpose other than to cause more confusion to those seeking guidance. It comes from a popular, yet poorly explained, online demo/tutorial by Sam Deering that is linked to/from many places.
The entire mess above can be removed and simply replaced by putting the .validate() method inside of the DOM ready event handler function...
$(document).ready(function() {
$("#aspnetForm").validate({ .... });
});

Jquery custom validation with Html 5 data attributes and default value

I am trying to build a custom client side jquery validation and trying to ignore default values that i generate from HTML5 data attributes
$('input, textarea').each(function () {
if ($(this).data('val-default')) {
$(this).focus(function () {
if (this.value == $(this).data('val-default'))
this.value = '';
});
$(this).blur(function () {
if (this.value == '')
this.value = $(this).data('val-default');
});
this.value = $(this).data('val-default');
}
});
So with the above code i can add default values to input and textarea elements like this
data-val-default="Type your first name here"
Placeholder attribute is unfortunately not an option yet
The problem now is that i am trying to validate these elements with Jquery validation like this
$.validator.addMethod("ignoreDefaultValues",
function (value, element) {
if ($(element).data('val-default'))
return !($(element).data('val-default') == element.value);
return true;
},
"Required field"
);
$('form#contact-form').submit(function (e) {
e.preventDefault();
if (!$(this).valid({
rules:
{
title:
{
ignoreDefaultValues: true,
required: true
},
description:
{
ignoreDefaultValues: true,
required: true
},
name:
{
ignoreDefaultValues: true,
required: true
},
email:
{
ignoreDefaultValues: true,
required: true
}
}
})) {
alert("NOT VALID!");
}
else
{
alert("IS VALID!");
//todo: ajax post to server
}
});
Here is an example of an input element
<input type="text" class="firstname" name="firstname" data-val-default="Type your first name here" data-val="true" data-val-required="*" />
The jquery validation seems to ignore the rules. if i test for example by typing an empty space it will validate and alert "NOT VALID" but it just ignores my custom validation.
What am i doing wrong?
Have i missed anything?
You need to setup the validation before the submit function. So instead of doing $(this).valid(...) in your submit handler, instead do this beforehand:
$('form#contact-form').validate( { //your rules
,
submitHandler:function(){
alert('Is Valid!');
$(this).submit(); //or submit via AJAX, or whatever you planned...
},
invalidHandler:function(){
alert('Is not valid!');
}
});

Categories

Resources