Why does my form submit and ignore validation? - javascript

I am trying to figure out why jquery validation does not stop my form from being submitted? When the submit button is pressed the form posts correctly but seems to ignore the validation error (This field is required) even if the input field is left blank.
The form
$(document).ready(function() {
$("#message").hide();
//Define your validation rules.
$(function() {
$("#myform").validate({
});
$("#submitButtonId").on("click", function(e) {
var formdata = $("#myform").serialize();
//Post form data
$.post('php_includes/simple_insert.php', formdata, function(data) {
//Process post response
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(500);
});
//Reset Form
$('#myform')[0].reset();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form class="form-inline" action="" id="myform" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="bill_cost"></label>
<div class="col-md-8">
<input id="bill_cost" name="bill_cost" type="text" placeholder="Bill Cost" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button type="submit" id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>

Try this, use submitHandler to do other things for a valid form:
$("#myform").validate({
submitHandler : function() {
var formdata = $("#myform").serialize();
//Post form data
$.post('php_includes/simple_insert.php', formdata, function(data){
//Process post response
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(500);
});
//Reset Form
$('#myform')[0].reset();
}
});

Remove a Required tag in bill cost text box.then you check the validation is ignored

Related

Bootstrap 4 manually invalidate input field natively

I want to make use of Bootstrap 4's form validation. From what I read you can invalidate a field by adding class 'is-invalid' - this works, but when I want to check the form validity using method checkValidity() it still says the form is VALID which is not what I expected. I was hoping of making use of the native bootstrap 4 functionality and not use plugins such as jquery validator etc.
$('#submit_button').on('click', function(e){
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if (form.checkValidity() === false) {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form is-invalid" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 1:
Using JQUERY you can use the .val() function
To get the value of the input field with id "taskname_in" use this code
$('#taskname_in').val()
Option 1 snippet:
$('#submit_button').on('click', function(e) {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if ($('#taskname_in').val() == '') {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 2:
Using form validator to check all input-fields at once.
Option 2 snippet:
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>
'is-invalid' does not make that particular field an invalid. it just applies CSS to look as it's invalid.
Result of HTMLElement.checkValidity() depends on its Constraint.
Suppose, you add field with 'required' constrain and you run checkValidity() on the form or field while it's empty, you will receive response as false, which means that a form or field is not valid.
In your case, just add required in your input field and you will receive response as invalid if you submit form while field is empty.
If you have the default Bootstrap validation code for the required fields:
$(".needs-validation").submit(function() {
var form = $(this);
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
});
You would just need to add another validation for example on input and use the setCustomValidity. For example if you want to check for equal values on password and confirm password:
if ($('form input[name="confirm_password"').length > 0) {
$('input[name="confirm_password"').on('change paste keyup', function() {
var password = $(this).closest('form').find('input[name="password"').val();
if($(this).val() !== password){
this.setCustomValidity('Passwords must match');
} else {
this.setCustomValidity('');
}
});
};
If you have an invalid-feedback message next to the input element it will show that message instead of the one you set here.

How to check if submitting form with jQuery if successful?

I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>

How to split a form data and assign to another values with jQuery?

I want to create a stripe.js form, first the data should be validated client-side then submitted to stripe.js to get token. Here is my full source code:
<!DOCTYPE html><html>
<head>
<?php
print_r($_POST);
?>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript" src="jquery.payment.js"></script>
<style type="text/css" media="screen">
.has-error input {
border-width: 2px;
}
.validation.text-danger:after {
content: 'Validation failed';
}
.validation.text-success:after {
content: 'Validation passed';
}
</style>
<script type="text/javascript">
jQuery(function($) {
$('[data-numeric]').payment('restrictNumeric');
$('.cc-number').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
$.fn.toggleInputError = function(erred) {
this.parent('.form-group').toggleClass('has-error', erred);
return this;
};
$('button[type="submit"]').click(function(e){
e.preventDefault();
var cardType = $.payment.cardType($('.cc-number').val());
$('.cc-number').toggleInputError(!$.payment.validateCardNumber($('.cc-number').val()));
$('.cc-exp').toggleInputError(!$.payment.validateCardExpiry($('.cc-exp').payment('cardExpiryVal')));
$('.cc-cvc').toggleInputError(!$.payment.validateCardCVC($('.cc-cvc').val(), cardType));
$('.cc-brand').text(cardType);
$('.validation').removeClass('text-danger text-success');
if ($('.has-error').length) { $('.validation').addClass('text-danger') } else { $('form').submit(); }
});
});
Stripe.setPublishableKey('pk_test_***');
jQuery(function($) {
$('#payment-form').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
</head>
<body>
<div class="container">
<form action="" method="post" id="payment-form" novalidate autocomplete="on">
<span class="payment-errors"></span>
<div class="form-group">
<label for="cc-number" class="control-label">Card number:<small class="text-muted">[<span class="cc-brand"></span>]</small></label>
<input id="cc-number" data-stripe="number" type="tel" class="input-lg form-control cc-number" autocomplete="cc-number" placeholder="•••• •••• •••• ••••" required class="col-md-2">
</div>
<div class="form-group">
<label for="cc-exp" class="control-label">Card expiry:</label>
<input id="cc-exp" type="tel" class="input-lg form-control cc-exp" autocomplete="cc-exp" placeholder="•• / ••" required class="col-md-2">
</div>
<div class="form-group">
<label for="cc-cvc" class="control-label">CVC:</label>
<input id="cc-cvc" data-stripe="cvc" type="tel" class="input-lg form-control cc-cvc" autocomplete="off" placeholder="•••" required class="col-md-2">
</div>
<button type="submit" class="btn btn-lg btn-primary">Submit</button>
<h4 class="validation"></h4>
</form>
</div>
</body>
</html>
This form for expiry uses just one field and it will be submitted as mm/yy to validator, validator works fine but after successfull validation, I want to split mm/yy separated and assign each of them to data-stripe="exp-month" and data-stripe="exp-year" respectively before submitting to stripe.js as those two data-stripe="exp-month" and data-stripe="exp-year" are required by stripe.js.
for validator I use this 3rd party script: https://github.com/stripe/jquery.payment/tree/master/lib
I see it has already a feature to split mm and yy here https://github.com/stripe/jquery.payment#paymentcardexpiryvalstring-and-fnpaymentcardexpiryval , but I have no idea how to use that function to split fom expiry date and assign them to data-stripe="exp-month" and data-stripe="exp-year"
Please advice how can I do this?
Stripe.js can accept expiry dates as a single argument: https://stripe.com/docs/stripe.js#passing-exp-dates
So you don't need to split the date. Just adding data-stripe="exp" to the cc-exp field should do the trick:
<input id="cc-exp" data-stripe="exp" type="tel" class="input-lg form-control cc-exp" autocomplete="cc-exp" placeholder="•• / ••" required class="col-md-2">

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

AJAX does not respond to form submission

I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!
Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});
The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready

Categories

Resources