Bootstrap validator - submitting fom without correct validation - ajax

Good Day!
I have a contact form that is using bootstrap validator.
I am able to get the (in)validation of the fields to show up as expected, but it does not seem like the submit button is "respecting" the (in)validation before submitting - the fields does not HAVE to be validated in order for the form to be submitted. I am using ajax in order to submit the form without realoding the entire page.
The ajax code should be located in the mashup.js file, of my contact test page!
(in case you have not already noticed it, I am a n00b - and would really appreciate the help:)
UPDATE: (This is the current code)
.html
<meta charset="utf-8">
<!-- Website Title & Description for Search Engine purposes -->
<title>Contact Form</title>
<!-- Mobile viewport optimized -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Content-Type -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- Bootstrap CSS -->
<link href="includes/css/bootstrap.min.css" rel="stylesheet">
<link href="includes/css/bootstrap-glyphicons.css" rel="stylesheet">
<!-- Responsive Navigator -->
<link rel="stylesheet" href="includes/nav/responsive-nav.css">
<!--<link rel="stylesheet" href="includes/nav/nav_styles.css">-->
<!-- Include Modernizr in the head, before any other Javascript -->
<script src="includes/js/modernizr-2.6.2.min.js"></script>
<!-- BootStrap Validator CSS -->
<link rel="stylesheet" href="includes/css/bootstrapValidator.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="includes/css/style.css">
</head>
<body>
<div class="container">
<div class="row">
<br>
<form id="html5Form" method="post" action='mail/mail.php'
class="form-horizontal"
data-bv-message="This value is not valid"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
<div class="form-group">
<label>Name</label>
<input class="form-control" placeholder="Name.." type="text" name="name" id="name"
data-bv-message="The username is not valid"
required data-bv-notempty-message="The username is required and cannot be empty"
pattern="^[a-zA-Z0-9]+$" data-bv-regexp-message="The username can only consist of alphabetical, number"/>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" placeholder="Email.." name="email" id="email" type="email" required data-bv-emailaddress-message="The input is not a valid email address"/>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" name="message" id="message" rows="7" required
data-bv-notempty-message="No empty message"></textarea>
</div>
<input type="submit" id="submit" name="submit" value="Send"/>
</form>
<div class="loading">
Sender melding...
</div>
<div class="success">
</div>
</div>
</div> <!-- End content -->
<!-- Include jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include Mashup -->
<script src="includes/js/mashup.js"></script>
<!-- Bootstrap JS -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- BootStrap Validator JS -->
<script src="includes/js/bootstrapValidator.min.js"></script>
<script>
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
});
</script>
</body>
</html>
.js
$(document).ready(function() {
$('form').on('submit', function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$(".loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$(".loading").fadeOut(function() {
//Display the "success" message
$(".success").text(data).fadeIn();
});
}
});
});
});
});
});

From looking at the provided Ajax example, it looks like you need to be watching for .on('success.form.bv'), not .on('submit'). So you would need to modify your event handler to look like this:
$('form').on('success.form.bv', function(e) { ... });
Hope this helps.

Related

Combine client-side and server-side validation in Bootstrap 4 form

I have a Bootstrap 4 form with an input field, called runname. I want to perform the following validation on the input field:
runname cannot be empty
runname cannot contain spaces
runnamecannot already be used previously
I already have the code for a form which gives an error, using custom Bootstrap styles if the input field is empty:
// JavaScript for disabling form submissions if there are invalid fields
(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);
})();
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container">
<div class="col-md-12 order-md1">
<form class="needs-validation" novalidate method="post" action="#">
<div class="form-group row">
<label for="inputRunname" class="col-sm-2 col-form-label">Run name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputRunname" name="runname" placeholder="Run name" required>
<div class="invalid-feedback">
Please enter a run name
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
</body>
</html>
And I have some Javascript to check if an input contains spaces:
function cannotContainWhiteSpace(input, errorId, name) {
var value = input.value;
var errMsgHolder = document.getElementById(errorId);
if (!(/^\S*$/.test(value))) {
errMsgHolder.innerHTML =
'The ' + name + ' cannot contain whitespace';
input.focus();
return false;
}
}
And I also have some Python code on my Cherrypy backend which does a lookup in the database to see if the runname already exists:
try:
myConnection = mysql.connector.connect(host=self.database['host'], user=self.database['user'], passwd=self.database['passwd'], db=self.database['db'])
cursor = myConnection.cursor(buffered=True)
# unless overriden by the force flag, check whether the runname has already been used before
if not force:
reusedrunquery = "SELECT run FROM logs WHERE run = %s AND errormessage IS NULL"
cursor.execute(reusedrunquery, (runname,))
if cursor.fetchall():
flag = True
cherrypy.session['reusedRun'] = True
myConnection.close()
except mysql.connector.Error as err:
return self.database_failure(str(err))
But I don't know how to cobble all these different parts together to get a form where I have both the two client-side validations and the server-side validation.
On Submit event, you should have a method in your backend that actually intercepts the request and I think there you should be able to make a connection with your backend's logic.
Here they are the steps:
Form compiled correctly
Http POST request starts onSubmit event
Back-end receives the request and applies further logic by gathering the data on the method in charge to receive the Http POST request
Otherwise, you may try to make an AJAX call on which there will be executed the client-side validations and then it will call the server-side method/class for checking that runname has been used already.
Most of the times I use custom styles to achieve this.
.invalid-feedback{
display:none;
}
.invalid .invalid-feedback {
display:block;
}
<form novalidate>
<div class="form-group">
<label>Label</label>
<input class="form-control" name="runname" type="text">
<div class="invalid-feedback"></div>
</div>
</form>
In Javascript
Validate the input controls and set css classes and message text.In your case, validate not empty, no spaces, and not already used[server side].
If invalid add the class invalid to parent form-group, and set the validation message inside invalid-feedback div next to the input control.

Datepicker, data-mask won't load after getting request from server

I created the main page that has 2 datepickers and 1 input mask for time. A button will trigger a GET request for a page with the same content to be loaded within a div. I have put all the js, CSS and function script on the main page.
At the main page, all the datepickers and input mask work correctly but the GET request got trigger and the new page is loaded, all the datepickers and input mask are not working.
Please help.
Date Picker and Input Mask Not Working
The MAIN PAGE Code
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- IN SUBFOLDER PLUGIN -->
<!-- Date Picker -->
<link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
<!-- JQuery 2.2.3 Compressed -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- datepicker -->
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
</head>
<body>
<form name="form1">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
<button type="submit" id="btnShow" name="btnShow"
onclick="showContent();return false;">
Show</button>
</form>
<br />
<br />
<div id="content2" style="display: none">
<!-- CONTENT HERE -->
</div>
<script>
$(function () {
//Date picker
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
});
$(function () {
//Time mask
$("[data-mask]").inputmask();
});
$(function () {
$("#btnShow").click(function () {
$("#content2").show();
});
});
</script>
<script>
function showContent() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content2").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ax_test.asp?", true);
xhttp.send();
}
</script>
The GET REQUEST Page ax_test.asp
<form name="form2">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
</form>
Manage to get it working by including the jquery in the showContent()
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- ALL script in subfolder plugins -->
<!-- Date Picker -->
<link rel="stylesheet" href="plugins/datepicker/datepicker3.css">
<!-- JQuery 2.2.3 Compressed -->
<script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- datepicker -->
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
</head>
<body>
<form name="form1">
<label>Date : </label>
<div>From :<input name="dt_DateFr" type="text" date-picker></div>
<div>To : <input name="dt_DateTo" type="text" date-picker></div>
<div>Time: <input id="txtOTOut" name="txtOTOut" type="text"
data-inputmask="'alias': 'hh:mm'" data-mask>
</div>
<button type="submit" id="btnShow" name="btnShow"
onclick="showContent();return false;">
Show</button>
</form>
<br />
<br />
<div id="content2" style="display: none">
<!-- CONTENT HERE -->
</div>
<script>
$(function () {
//Date picker
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
});
$(function () {
//Time mask
$("[data-mask]").inputmask();
});
$(function () {
$("#btnShow").click(function () {
$("#content2").show();
});
});
</script>
<script>
function showContent() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content2").innerHTML = xhttp.responseText;
$("[data-mask]").inputmask();
$("[date-picker]").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
}).datepicker("setDate", new Date());
}
};
xhttp.open("GET", "ax_test.asp?", true);
xhttp.send();
}
</script>
</body>
</html>

Bind visible to whether field (in kendo observable) has changed or not?

I would like to show or hide elements of my kendo template based on whether or not a field in my model has changed or not.
First attempt:
<input type="text" data-bind="value: schedulerEventFieldOne"/>
<input type="text" data-bind="value: schedulerEventFieldTwo, visible: schedulerEventFieldOne.dirty"/>
Attempt two is to have a 'schedulerEventFieldOneOrigValue' field added to my model, then doing this:
<input type="text" data-bind="value: schedulerEventFieldOne"/>
<input type="text" data-bind="value: schedulerEventFieldTwo, visible: schedulerEventFieldOne != schedulerEventFieldOneOrigValue"/>
But this gives me an error stating that schedulerEventFieldOne is not defined. It seems that it doesn't like the equality test. Which is odd since, using a < o r > test seems to work fine: "visible: schedulerEventFieldOne > 0"
Is there a way to accomplish my task using the kendo binding? Or will I have to resort to jQuery again?
You do not state any concern, so why dont you do it on the view model with the second approach? It's possible to do this i believe :
$(document).ready(function() {
var vm = kendo.observable({
form: {
country: ""
},
original: {
country: ""
},
isDisabled: function() {
return this.get("form.country") != this.get("original.country");
},
save: function() {
}
})
kendo.bind($("#test"), vm);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/angular.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/jszip.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/kendo.all.min.js"></script>
</head>
<body>
<div id="test">
<input type="text" data-bind="value: form.country" />
<button data-bind="click:save, visible:isDisabled">Save</button>
</div>
</body>
</html>

JQuery Mobile Validate after changePage

I'm using JQuery Mobile with a form that changes server side. I need to reload the page so the most recent form is included on the page. The form also needs validation.
I'm able to get the validation to work once but once until a submit. The page successfully is refreshed and the form appears but the validation is gone and if I submit, a standard submit is done instead of a changePage.
The on pageinit seems to be firing every time. I've been pulling my hair out on this one. It seems like this should be so simple.
<?php //
session_start();
if (isset($_SESSION['mytest']))
$_SESSION['mytest']++;
else
$_SESSION['mytest'] = 1;
$s = $_SESSION['mytest'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>mytestout</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="//code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"> </script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
</head>
<body>
<div data-role="page" data-theme='b' id="testit" >
<div data-role="content" class="content" id="cart" style="margin-top: 25px; margin-left: 40px">
<p> counting session var = <?=$s?> </p>
<form id="myform">
<input type="text" name="myname">
<input type="submit">
</form>
</div>
</div>
<script>
function submitme(e) {
$.mobile.changePage( "#testit", { transition: "slideup", changeHash: false, reloadPage: true, allowSamePageTransition: true });
}
$(document).on('pageinit', function(){ //
$("#myform").validate( {
rules: {
myname: "required"
}
,submitHandler: function(e) { submitme(e);}
});
});
</script>
</body>
</html>
The problem here is the 'pageinit' event, which runs just once per page (its also deprecated). You'd have to use the pagecontainershow event, which runs each time the page is shown. That should initialize the form validation again, making it work for each time its rendered. Note that I haven't tested that solution, yet.

Redirecting immediately with javascript

I have a problem redirecting a page with javascript. I want to redirect the page after clicking a button, but it is redirecting it automatically.
Why is that?
window.onload=initAll;
function initAll(){
if(window.addEventListener) {
document.getElementById('check').addEventListener("click",redirection,false);
} else if (window.attachEvent){
document.getElementById('check').attachEvent("onclick", redirection);
}
function redirection(){
window.location.href='http://www.google.com';
}
}
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="glavna.js"></script>
</head>
<body>
<div id="wrapper">
<form action="glavna.html">City:<input id="city" type="text"/>
Price: From:<input type="text" id="from"/> To:<input type="text" id="to"/>
Refresh in min :<input type="text" id="refresh"/>
<button id="check" >Search</button>
</form>
</div>
</body>
</html>
this can be done with window.location.href what it does
// similar behavior as clicking on a link
window.location.href = "you want to redirect";
window.location is location object. To redirect Use window.location.href instead

Resources