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

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.

Related

Unable to Programmatically invoke the invisible recaptcha challenge by ID

We have a set up with multiple forms on a single page. We are rendering each recaptcha successfully, however I'm struggling to invoke the recaptcha challenge programatically targeted to an ID.
Looking at the docs (https://developers.google.com/recaptcha/docs/invisible#programmatic_execute) my understanding is that I can pass an ID with the execute command so the response is filled into g-response within the correct form, otherwise the response defaults to the first g-response it finds on the page (which is no good for anything other than the first form on the page).
I've tried it with a slightly modified version of Googles own example, however we get the error message 'Invalid site key or not loaded in api.js: recaptcha123' even though the key is correct.
Does anyone have any idea how we might get this working?
<html>
<head>
<script>
function onSubmit(token) {
alert('thanks ' + document.getElementById('field').value);
}
function validate(event) {
event.preventDefault();
if (!document.getElementById('field').value) {
alert("You must add text to the required field");
} else {
grecaptcha.execute('recaptcha123');
}
}
function onload() {
var element = document.getElementById('submit');
element.onclick = validate;
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form>
Name: (required) <input id="field" name="field">
<div id="recaptcha123" class="g-recaptcha"
data-sitekey="XXXXXXXXXXXXXXXX"
data-callback="onSubmit"
data-size="invisible"></div>
<button id="submit">submit</button>
</form>
<script>onload();</script>
</body>
</html>
The following code works:
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script>
var onSubmit = function(token) {
console.log('success!');
};
var onloadCallback = function() {
widgetId1 = grecaptcha.render('recaptcha', {
'sitekey' : 'XXXXXXXXXXXXXXXXXX',
'callback' : onSubmit
});
};
</script>
</head>
<body>
<script src="/wp-content/themes/kc_water_care_services/js/pristine.min.js"></script>
<form action="?" method="POST" id="contactForm">
<div class="form-group">
<label for="name">Name (required)</label>
<input type="text" required data-pristine-required-message="Please enter your name"
id="name" name="name" />
</div><!--/.form-group-->
<div id="recaptcha" data-size="invisible"></div>
<input id="submit" type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
</body>
</html>
<script>
var form = document.getElementById("contactForm");
// create the pristine instance
var pristine = new Pristine(form);
form.addEventListener('submit', function (event) {
event.preventDefault();
// check if the form is valid
var valid = pristine.validate(); // returns true or false
if(valid == true){
grecaptcha.execute(widgetId1);
}
});
</script>
Turns out the id doesn't refer to the css ID, it refers to an ID created when you use the render function.

Bootstrap validator - submitting fom without correct validation

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.

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.

Dart: AJAX form submit

Please note: I am not interested in using Polymer for this; I want to use "pure" Dart!
I am trying to build a simple sign-in screen for my Dart app, and am having difficulty getting the two form variables (email and password) to POST to the server-side:
Here's my main HTML file (myapp.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sign in</title>
<link rel="stylesheet" href="assets/myapp/myapp/myapp.css">
<link rel="stylesheet" href="assets/myapp/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="signinForm" method="POST" class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" name="email" placeholder="Email address">
<input type="password" class="input-block-level" name="password" placeholder="Password">
<button class="btn btn-large btn-primary" id="signinBtn" type="submit">Sign in</button>
</form>
</div>
<script type="application/dart" src="myapp.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
Here's my main Dart file (myapp.dart):
import 'dart:html';
void main() {
querySelector("#signinForm")
..onClick.listen(handle);
}
void handle(MouseEvent mouseEvent) {
mouseEvent.preventDefault();
FormElement formElement = mouseEvent.target as FormElement;
var url = "http://localhost:8080/myapp/signinService";
var request = HttpRequest.request(
url,
method: formElement.method,
sendData: new FormData(formElement)
).then(onDataLoaded);
}
void onDataLoaded(HttpRequest req) {
String response = req.responseText;
if(response == 1)
window.alert("You are signed in!");
else
window.alert("Sign in failed. Check credentials.");
}
When I run this in a browser I see the sign in screen appear, but when I click the signin button nothing happens, and Firebug throws a bunch of errors on the cross-compiled, obfuscated, minified JavaScript:
: CastError: Casting value of type qE to incompatible type Yu
I want this to be an AJAX request so that the user does not have to experience a page reload (the intent here is to be a single page app).
Any ideas as to what's going on here? I'm almost 100% confident the issue isn't on the server-side, so for now I'm omitting to post server code. But I'll update my question with server code if need be.
here is an example how to do this
Forms, HTTP servers, and Polymer with Dart
When you change
void main() {
querySelector("#signinBtn")
..onClick.listen(handle);
}
to
void main() {
querySelector("form")
.onSubmit.listen(handle);
}
you have access to target
void handle(Event event) {
event.preventDefault();
FormElement form = event.target as FormElement;
...
}

ajax form input file upload loading a separate page in codeigniter

I am using
<script src="http://malsup.github.com/jquery.form.js"></script>
for my ajax form upload.
When I upload file without the Codeigniter framework this works fine. But when I used it within the frame work it shows me the following error :-
HTTP wrapper does not support writeable connections
plus it is actually loading a separate page
Here's my code :-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
clearForm: true,
resetForm: true
};
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
//alert("Thank you for your comment!");
});
$('#myForm').ajaxForm(options);
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="comment.php" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<br />
<textarea name="comment"></textarea>
<br />
<input type="file" value="Share a Pic" name="file" id="file" />
<br />
<input type="submit" value="Submit Comment" />
</form>
</body>
For Codeigniter I changed the action to
site/submit_myform
So it loads site/submit_myform. Site being my controller. other values are being stored in the database
Thanks
The ajax part isn't working if the page is redirecting. You need to return false; during the on submit to prevent the page from redirecting.
I would suggest following the ajaxSubmit()example provided in the form plugin.

Resources