Form validation with express - javascript

I have read that form validations on client-side is not enough to prevent any malicious actions from users. For that case i have read that is needed to validate the form on the server-side too. Since i am first time using express, can someone give me a clue for what i need to do?
I'm leaving here the html form and the js validation function. My form doesn't have the "action" and "methods" for test purposes. I know that the "action" leads to my validation page and the method is POST on this specific case.
Is it safer to create a module for the validation and then call it on the server.js? or can i code it inside of the server.js?
HTML
<div class="containerfrm" id="frmcntn">
<!--Form Creation with method POST, JavaScript input validations and php file validation-->
<form action="" method="" class="cntbox" id="formBoard" name="formOfBoard" onsubmit="validateIndexForm(event)">
<!--Close Button of the pop up-->
<div class="righttopicon" onclick="closeForm()">
<img src="images/square-x.png" alt="close icon">
</div>
<!--Form with the necessary inputs (Name of the Board, IP Address, Port and upload file). All the inputs are required-->
<div class="col-100">
<h3>Add new board:</h3>
</div>
<!--Input for the boards name with max length of 50 characters-->
<div class="col-75">
<label for="bname">Name of the Board: *</label><br>
<input type="text" id="boardname" name="boardname" placeholder="Ex: Board 1" maxlength="50">
</div>
<!--Input for the IP Address that can only accept IP's and with a max length of 15 characters-->
<div class="row">
<div class="col-75">
<label for="ipadd">IP Address: *</label><br>
<input type="text" name="ipadd" id="ipaddress" placeholder="Ex: 192.168.1.1" maxlength="15">
</div>
</div>
<!--Input for the Port that can only accept numbers with a max length of 4-->
<div class="row">
<div class="col-75">
<label for="portnum">Port: *</label><br>
<input type="text" name="portnum" id="portnum" placeholder="Ex: 8080" maxlength="4" minlength="2">
</div>
</div>
<!--Input for the upload of the boards image that can only accept .png files-->
<div class="row">
<div class="col-75">
<label for="imgadd">Upload image:</label><br>
<img src="images/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
<input type="file" id="myFile" name="filename" onchange="fileValidation(event)">
</div>
</div>
<!--'Save' and 'Discard' buttons -->
<div class="row">
<div class="col-80">
<div class="btnformcontainer">
<input type="submit" class="btnfrm btnconfrm" value="Save">
<div class="btnfrm btndel" onclick="discardValues()">Discard</div>
</div>
</div>
</div>
</form>
</div>
JS Validation
function validateIndexForm(event){
let x = document.getElementById("boardname").value;
let y = document.getElementById("ipaddress").value;
let z = document.getElementById("portnum").value;
let w = document.getElementById("myFile").value;
let ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
if(x == ""){
//prevent the form submit
event.preventDefault();
alert("Please insert the boards name");
return false;
}
if(!y.match(ipformat) && !y === "localhost"){
//prevent the form submit
event.preventDefault();
alert("Please insert a valid IP address");
return false;
}
if(z != isNaN() && !(z > 0)){
//prevent the form submit
event.preventDefault();
alert("Please insert the correct port");
return false;
}
if(w == ""){
event.preventDefault();
alert("Please insert a valid image");
return false;
}
return x, y, z, w;
}
The uploaded file is getting validated on other function successfully.

Whether you create a module for the validation and bring it in to your server file or code the logic directly into your server file, it does not affect security and produces the same behavior.
For securing your server-side form validation, I recommend a tool like express-validator in combination with a body-parser.
Check out this article for a hands-on approach to the above mentioned setup.

You can just do the same thing in the post request code on your server side.
Ex:
app.post('/register', (req, res) => {
let username = req.body.username;
let password = crypto.createHash('sha256').update(req.body.password).digest('base64');
let repassword = crypto.createHash('sha256').update(req.body.repassword).digest('base64');
if(password != repassword) return res.redirect('/login');
});
You can also do queries in your redirect like this:
res.redirect('/login/?e=4&t=l');
And parse them client side to display errors like passwords do not match.

Related

custom error message shows and disappears on submit

I am using flask, html, css and javascript. So what I did was enter a error message in my login form as a new and set display: none. I validate the input credential by comparing values from a SQLite database i set previously. This validation is done inside the flask. When the form is submitted, it is validated inside the flask, however I created a javascript that changes the styling for the error message to display: block. This would show the error message for incorrect fields and the correct input users will be redirected to a new page and hence they wont see the error.
So I was hoping that the error message shows after the form is submitted for the login and the users that key in the right information will be redirected.
Flask:
#app.route('/', methods=['POST', 'GET'])
def tutor_login():
tutor_login_form = LoginAccount(request.form)
if request.method == 'POST' and tutor_login_form.validate():
session.pop('user', None)
admin_account = Admin.query.all()
tutor_account = Tutor.query.all()
for i in admin_account:
admin_id = i.admin_id_num
for j in tutor_account:
tutor_id = j.tutor_id_num
if admin_id == tutor_login_form.id_num.data:
admin_info = Admin.query.filter_by(admin_id_num=tutor_login_form.id_num.data).first()
admin_pass = admin_info.admin_password
if admin_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('admin_main'))
elif tutor_id == tutor_login_form.id_num.data:
tutor_info = Tutor.query.filter_by(id_num=tutor_login_form.id_num.data).first()
tutor_pass = tutor_info.tutor_password
if tutor_pass == tutor_login_form.password.data:
session['user'] = tutor_login_form.id_num.data
return redirect(url_for('retrieve_tutor_account'))
return render_template('tutorlogin.html')
HTML:
<form class="" action="" method="POST" onsubmit="validate()">
<!-- Input fields -->
<div class="form-group mt-3">
<label for="id_num">Enter Tutor ID:</label>
<input type="text" class="form-control" id="id_num" placeholder="Enter Tutor ID" name="id_num">
</div>
<div class="form-group my-3">
<label for="password">Enter Password:</label>
<input type="password" class="form-control password" id="password" placeholder="Enter Password" name="password">
</div>
<div class="mb-3 text-center" id="error">
ID or Password entered is invalid! Please try again.
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-customized">Login</button>
</div>
<div>
<p class="text-center my-3">Forgot your password? <br> Click here to reset</p>
</div>
</form>
Javascript:
<script>
var error = document.getElementById('error');
function validate(){
error.style.display = "block";
}
</script>
If you want to validate the credentials without a page reload, you need to use Ajax requests.
Where on clicking Submit, the JavaScript will first check if all fields all valid and filled and then send an Ajax request to the Flask app.
Depending on the response of the query you can either show a error message or redirect user to the page you want.
Here's a YouTube video for reference - https://www.youtube.com/watch?v=UmC26YXExJ4

Submit button taking me to link that states HTTP ERROR 405. How do I prevent this, so i can allow it to work the way it is intended to?

I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}

form.checkValidity checking that two password fields match

First post here so please be gentle. I'm trying to self learn how to write a responsive website for a local club. Is there any way of checking that two password fields are identical and error accordingly using the bootstrap 4 method of form validation? I can do it server side but since I am doing a fair amount of client side form validation, it would be nice if I could check that the passwords were the same before submitting the form.
<form class="container" id="form-validation" method="post" action="./register.php" novalidate>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation1">Username</label>
<input type="text" class="form-control" name="username" id="validation1" placeholder="Username" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation2">Password</label>
<input type="password" class="form-control" name="pwd1" id="validation2" placeholder="Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation3">Confirm Password</label>
<input type="password" class="form-control" name="pwd2" id="validation3" placeholder="Re-enter Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters and match original Password
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<button class="btn btn-success" type="submit" value="Send" name="registerbtn">Register</button>
</div>
</div>
</form>
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
Using this should work.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You can achieve this validation through the JavaScript constraint validation API, it's a customError, which you can set prior to form submission.
I'll provide the example for BootStrap4 and assume jQuery as an optional but common BootStrap dependency to abbreviate $("#pw1").val()
The HTML
<form>
<div class="form-group">
<label for="pw1">Password</label>
<input type="password" class="form-control"
id="pw1" placeholder="Password"
required minLength=8>
</div>
<div class="form-group">
<label for="pw2">Repeat Password</label>
<input type="password" class="form-control"
id="pw2" placeholder="Password" aria-describedby="pwHelp"
required minLength=6
oninput="validate_pw2(this)">
<small id="pwHelp" class="form-text text-muted">Please repeat your password</small>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
The Script
<script>
function validate_pw2(pw2) {
if (pw2.value !== $("#pw1").val()) {
pw2.setCustomValidity("Duplicate passwords do not match");
} else {
pw2.setCustomValidity(""); // is valid
}
}
</script>
The important parts are the oninput in #pw2, which attempts to validate every time the value its changed. Then the setCustomValidity call provides the user message displayed when invalid, the empty string is used when it is now valid.
You can put a check to verify the password values are the same and abort the submission if they're not.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You would just change the alert window to show error text to your user. Here is an example to see how it would look: https://jsfiddle.net/aq9Laaew/55184/
Another suggestion would be to use something like jQuery so that the syntax is less cumbersome to deal with. But that's up to you.
From your code checkValidity() will check only the validity of the form HTML5 constraint (required, format, pattern, min, max), but there is no constraint for verify password. In reality this is like comparing if the content of 2 fields is the same. Also if you want to cancel the form submission, you also needs to return false; at the end. Normally HTML5 will not submit a form that has validation errors.
In you case I will suggest make a validation while you are typing on the validation field, and disable the submit button until the passwords match.
document.getElementById('validation3').addEventListener('keyup',function(e){
if(this.value !== document.getElementById('validation2').value){
document.getElementById('validation4').disabled=true;
this.classList.replace('pass','nopass');
}else{
document.getElementById('validation4').disabled=false;
this.classList.replace('nopass','pass');
}
}
You will need to assign an id='validation4' to the submit button. To make visual changes you could create a CSS rules to handle this ('pass','nopass').

Get default validation input email on old browsers

I'm trying to build a simple contact form for the newsletter subscription, the CF has just one input field (email) and the submit button. I used type="email" of HTML5 to check the the email and on the new browsers I get the default validation message:
This doesn't happen when I use older browsers obviously so I used the JS alert in case the user is using the old browsers, but this is not what I'd like.
I would like to get the same message (browser default) on all the browsers.
Here my code:
HTML
<div class="newsletter-wrap-flex margin-top-div">
<div class="newsletter-title">
<span>
NEWSLETTER
</span>
</div>
<div class="newsletter-form">
<form id="newsletter-cf" method="post" action="">
<input id="contact-email" type="email" placeholder="Your email" required/>
<input id="contact-send" class="submit" type="submit" value="Subscribe" />
</form>
<div id="message-sent">Congratulation! Your request has been sent.</div>
</div>
</div>
JS
function checkEmail(inputvalue) {
var pattern = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return pattern.test(inputvalue);
}
$('#newsletter-cf').submit(function () {
var email = document.getElementById("contact-email").value;
if (!checkEmail(email))
{
alert('Email address is invalid');
return false;
}
$("#newsletter-cf").slideUp("slow");
$("#message-sent").slideDown("slow");
return false;
});
I've read there could be some ways like Modernizr but I've never used them before so I don't really know how to start.
Any suggestions?

Re: Form validation not working

I am a newbie regarding backend technology and want to thank you for your patience ahead of time. I am developing a website with php includes, in which one link is a contact form (see below). I need the fields in the forms to be validated using javascript (see below for my code). I am also using a local server (WAMP). When I load the page containing the form and enter the wrong amount of characters or leave the form fields blank, there is no error message. Any help is greatly appreciated...thank you again for your patience.
php document(contact.php)
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="form2.js"></script>
<?php require 'Includes/Header.php'; ?>
<div class="wrapper">
<div id="contact-form">
<h5>Contact Form</h5>
<form method="post" action="contact.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">Send</button>
</form>
<div class="clear"></div>
</div>
</div>
<?php require 'Includes/Footer.php'; ?>
Javascript(form2.js)
function validate(form){
var name = form.name.value;
var name = form.email.value;
var name = form.message.value;
if (name.length == 0 || name.length > 200)
{
alert ("You must enter a name.");
return false;
}
if (email.length == 0 || email.length > 200)
{
alert ("You must enter a email.");
return false;
}
if (message.length == 0)
{
alert ("You must enter a message.");
return false;
}
return true;
}
It doesn't look like your calling the validate() function. Try something along the lines of:
<form method="post" action="contact.php" onsubmit="return validate()">
Follow this example from w3schools... it seems to be exactly what you are trying to do. You never assigned the values to variables either. Assign a name to the form (e.g., name="myform") and reference the variables the same way in the example.
var name = document.form["myform"]["name"].value;

Categories