custom error message shows and disappears on submit - javascript

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

Related

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 validation with express

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.

How to show a success message to redirected page after submitting from another page using jquery in JSP?

I have a reset password form. After submitting it, it redirects to login page. However, it doesn't show any success message upon getting the successful reset password. And, I'm uncertain how can I do this as these are two different jsp files. And even if the login page uses the reset password javascript code, it still can't be able to show the conditional message. I am using java spring boot, jquery and javascript. This is my code:
resetPassword.js
$(".resetPassword").on('submit', function (e) {
e.preventDefault();
var password = $("#pass").val();
var confirmPass = $("#confirmPass").val();
if(password !== confirmPassword){
$(".perror").show();
}
else {
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
});
resetPassword.jsp
<form:form action="/reset_password" method="POST" class="resetPass" modelAttribute="resetPassword">
<div class="alert alert-danger perror" role="alert" style="display: none">Password not match</div>
<form:input type="hidden" path="token" />
<div class="form-group-row ">
<label htmlFor="passwordReset">Password</label>
<input type="password" id="pass" path="password" placeholder="Password" required/>
</div>
<div class="form-group-row ">
<label htmlFor="confirmPasswordReset">Confirm Password</label>
<input type="password" id="confirmPass" placeholder="Confirm Password" required/>
</div>
<button type="submit" class="btn btn-danger">Submit</button>
</form:form>
Now, this is the login.jsp in where I want the successful message which currently now I've been showing from alert box however that seems not a good design.
login.jsp
<form:form action="/login" method="POST" modelAttribute="user" >
<div class="alert alert-success successfulResetPassword" role="alert" style="display: none>Your password changed successfully. Please login using your email and password</div>
<input type="text" id="email" name="email" placeholder="email" required/>
<input type="password" id="password" name="password" placeholder="pass" required/>
</form:form>
now all I want, is to show the div class=successfulResetPassword after a user reset the password show that the display alter it's value to visible. But I haven't found any good way to this as reset password is using a different js file and from that submit button I'm redirected the whole scenario to login page. Even if the login page can access that js page still it can't have the value of changing display property :
$("#successfulResetPassword").show();. I tried to modify my code like this till now :
resetPassword.js
else {
$("#successfulResetPassword").show(); //it could've shown the msg, but can't because it's in button submit condition after redirected to login page which has no **resetPassword** class
alert("Your password changed successfully");
$(this).unbind('submit').submit();
}
And this is my backend code:
#PostMapping("/reset_password")
public String resetPasswordSubmit(Map<String, Object> model, #ModelAttribute("resetPassword") ResetPasswordDTO resetPassword){
model.put("pageTitle", Constant.PAGE_TITLE);
GenericResponse response = loginService.changePassword(resetPassword);
if(response.getStatusCode() == 200){
return "redirect:/login";
}
model.put("error", "error");
return "resetPassword";
}

Pressing Enter doesn't work with AngularJS

I am having a problem with using 'enter button' on the keyboard with an angular js login form. I know this question is asked before but I believe that my problem is a bit different because I tried almost everything written on the stackoverflow questions.
So, I just want to be able to hit enter and submit the form with only using the enter key on keyboard.
Here is login html:
<!-- BEGIN LOGIN FORM -->
<form ng-submit="loginCtrl.login()" class="login-form">
<h3 class="form-title">Sign In</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Company/username"
ng-model="loginCtrl.username" name="username"/>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password"
ng-model="loginCtrl.password" name="password"/>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success uppercase" value="Login">
</div>
</form>
<!-- END LOGIN FORM -->
and here is my login:
self.login = function() {
var result = self.username.split("/");
var account = result[0];
var userId = result[1];
UserService.login(userId, self.password,account).then(function(user) {
self.userAccount = user;
$state.go('home');
}, function(err) {
alert("Authentication failure: Please check your credentials. ")
});
I get user name as "companyName/Username" so it is like:
amazon/bigboby
I'm pretty sure your problem is caused by this <button> tag:
<button class="close" data-close="alert"></button>
The answer is found in the documentation:
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
Note the comment about how it looks for an ng-click handler on the first button. When you are pressing ENTER to submit the form, Angular looks at the form and sees that button. It would execute the ng-click handler on that button (if it had one).
If you include the type attribute on the button, you can prevent that and let it find the actual submit button:
<button type="button" class="close" data-close="alert"></button>

php web page password empty validation

I wanted to check if the username and password fields are empty.
If they are empty it should give a error message box and the message box should contain a message and a ok button.
When user clicks the ok button the msg box should close and user should see the login page.
For that i wrote the below code. but after pressing the ok button on error message box the web page address is remaining same but the content is not getting displayed , full white page is displayed.
you do refresh and page comes back.
This is the file i am opening in browser register.php
<?php
// configuration
require("../includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// else render form
render("register_form.php", ["title" => "Register"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// TODO
if (empty($_POST["username"]) || empty($_POST["password"]))
{
$message = "Username and/or Password empty.\\nTry again.";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
And this is the form file register_form.php
<form action="register.php" method="post">
<fieldset>
<div class="form-group">
<label>Username :</label>
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<label>Password :</label>
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<label>Password :</label>
<input class="form-control" name="confirmation" placeholder="Retype-Password" type="password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Register</button>
</div>
</fieldset>
</form>
i want to see login page after clicking the ok button on the message box i do not want to see white page. please help

Categories