I am making a login page with validation as part of my school project. Please note: I am aware this is unsecured I just want to get the method correct first then I am going to add a hash function I want to compare the user's input in the form with my default username and password and output an error message if they do not match, or redirect to a different webpage if they both do match.
This is the code I have so far:
<form>
<label for "username"> Username: </label>
<br>
<input type = "text" id = username>
<br>
<label for "password"> Password: </label>
<br>
<input type = "password" id = password>
<br><br>
<input type="submit" value="Submit" onclick = validationFunction()>
<br>
<div id = "error"></div>
<script>
var x = document.getElementById("submit");
x.addEventListener("click", validationFunction());
event.preventDefault()
function validationFunction() {
var inputUsername = document.getElementById(username);
if (inputUsername == "admin") {
} else if (inputUsername != "admin") {
document.getElementById("error").innerHTML = "incorrect username or password";
}
var inputPassword = document.getElementById(password);
if (inputPassword == "password"){
} else if (inputPassword != "password"){
document.getElementById("error").innerHTML = "incorrect username or password";
}
}
event.target.submit();
</script>
</form>
The code works for a second but the page immediately refreshes after showing the output - I am unsure of how to rectify this so that it remains on screen for the user to read and then enter the correct username and password combination.
I am also getting the error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
for the line:
x.addEventListener("click", validationFunction());
I thought I assigned the variable x to the submit button element, is there anything I need to add?
When you submit a form the default behaviour you get is page refresh. In order to prevent it you need to use the event function preventDefault first thing when you submit it. event.preventDefault().
<form onsubmit="onSubmitFunc(event)">
<input type="text">
<input type="submit">
</form>
function onSubmitFunc(ev) {
ev.preventDefault()
}
Related
I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript
var myStorage = window.localStorage;
let accounts = [{
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
}];
myStorage.setItem("account", accounts);
//check login account
var checkLogin = function() {
let uname = document.getElementById("Uname").value;
let pass = document.getElementById("Pass").value;
if (uname == "admin" && pass == "admin123!") {
myStorage.setItem("user", {
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
});
alert("Login admin");
window.location = "../account/myaccount.html";
alert("redirect");
} else {
myStorage.setItem("user", undefined);
document.getElementById("incorrectAccount").style.color = "red";
document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
}
};
<form id="login" method="post" onsubmit="return checkLogin();">
<div>
<label><b>Username:
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="admin"><br><br>
</div>
<div>
<label><b>Password: </b></label>
<input type="Password" name="Pass" id="Pass" placeholder="admin123!"><br><br>
</div>
<div>
<input type="submit" name="log" id="log" value="Log In"></a>
<span id="incorrectAccount"></span>
<br><br>
</div>
<div>
<input type="checkbox" id="check">
<span>Remember me</span>
</div>
<div>
Forgot Password?
<br><br>
Register
</div>
</form>
After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
event.preventDefault();
and
document.querySelector('form').addEventListener('submit', checkLogin);
Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.
onsubmit="return checkLogin();"
You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
function myRedirect() {
location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>
Only been studying a couple of months, trying to learn the basics. I have created a form, I have tried to input javascript to show an error message when the submit button is clicked, but there is incomplete information. I have only tested this on the user name field so far, but my message "Name is required" isn't showing when i click submit but leave the username empty.
I have followed this code from a youtube video, and as far as i can see it looks okay! i have put the js in a syntax validator too. I originally had the IDs on the divs and not the input tag, so changed this.
const name = document.getElementById('name')
formZ.addEventListener('submit', (e) => {
let messages = []
if (name.value === '' || name.value == null) {
messages.push('Name is required')
}
if (messages.length > 0) {
e.preventDefault()
error.innerText = messages.join(', ')
}
})
<div id="errorMessage"> </div>
<form action="/" method="GET" id="formZ">
<div id="form">
<div>
<input type="text" placeholder="Username" required="" class="inputField" id="name">
</div>
<div id="submitArea">
<button type="submit" class="submitButton">Submit</button>
</div>
</div>
</form>
So what i'm aiming for is, a user tries to submit the form without filling in their name, an error message pops up to say "Name is required".
You are not getting the expected result because the name field is required, which means that if the field is left blank, no submission would happen.
Since the only checks you did on submit are that name is not empty or not null, and the browser automatically prevent the user from submitting the form when name is empty, you don't see the error message.
Iv'e added a condition for adding errors when the user enter the string a. Try to enter a and submit and you will see your expected result.
Plus in your code you are missing a few variables (error and formZ) so I've added them as well.
The way I see it there are 2 options for you:
1. Add different error cases, ones that don't check only empty values.
2. Don't use the required property.
Anyway I'm suggesting you to read about form validation, it might help you.
const name = document.getElementById('name');
const error = document.getElementById('errorMessage');
const formZ = document.getElementById('formZ');
formZ.addEventListener('submit', (e) => {
let messages = [];
if (name.value === '' || name.value == null || name.value === 'a') {
messages.push('Name is required');
}
if (messages.length > 0) {
e.preventDefault()
error.innerText = messages.join(', ')
}
})
<div id="errorMessage"> </div>
<form action="/" method="GET" id="formZ">
<div id="form">
<div>
<input type="text" placeholder="Username" required="" class="inputField" id="name">
</div>
<div id="submitArea">
<button type="submit" class="submitButton">Submit</button>
</div>
</div>
</form>
I'm trying to send messaging to the user that a field is required if they fail to input a value. I want the error to be displayed on the field itself, rather than a global error message at the top of the page.
If I do not enter any data into the form, it still allows submission. However, if I do not enter a username but I do enter mismatched passwords, the username field receives the validation message "Passwords do not match".
So, it appears to me, that for some reason my code to check if the input is null is not passing as True and so the function continues to my next condition.
Why isn't this function catching nulls?
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"
oninput="checkNull(this)" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password" oninput="checkNull(this)"
id="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmPassword" placeholder="Confirm Password" type="password"
oninput="check(this)" id="confirmPassword">
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
} else {
input.setCustomValidity('');
}
}
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
}
else {
input.setCustomValidity('');
}
</script>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I've tried some additional troubleshooting. I split my functions out, one to check for matching passwords, one to check for no input. I realized that by calling them in the same function I was comparing each to the password which is a problem.
As a sanity check, I then set to check for a specific string "foo". When passing in "foo", the error displays as expected, so I know at least the function is getting called.
I then tried to use "===" to compare the value rather than "==", but that didn't work either.
Code updated to reflect most recent changes.
When submit your form, it is not calling check() function. So, if you not touch any input, they will not be validated.
You can solve this by adding onsubmit="return validate()" to <form /> tag:
<form action="/register" method="post" onsubmit="return validate()">
Your validation function could be simple as:
var isValid = true;
function validate() {
isValid = true;
document.querySelectorAll('.form-control').forEach(check);
return isValid;
}
Notice the return keyword. When return value is false the submitting action will be cancelled. check() function should also mutate isValid variable:
function check(input) {
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
isValid = false;
}
else if (input.type == 'password' && input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
isValid = false;
}
else {
input.setCustomValidity('');
}
}
Also, you should only check if passwords are the same if you are validating a password input.
You can accomplish this by adding the extra condition to password validation: input.type == 'password'
You are calling your check method onchange, if you do not enter any text in the username field, your check method will not be called. So, the simple way to do this is to add required attribute on all your fields.
If you want to do it using JS, look at onsubmit method that gets triggered when the form's submit button is clicked.
Also, you should have three different methods for validating each of your fields. It will be hard to maintain and you will be cramping up one method with various checks.
You are using deprecated techniques here.. You should never attach a function to a form element in-line (within the html tag).
When it comes to checking password on keyup, you could use something like this with jquery:
var pwInputs = $(this).find('input[type=password]');
$('input[type=password]').keyup(() => {
pwarr = new Array();
pwInputs.each(function() {
pwarr.push($(this));
});
if (pwarr[0].val() != pwarr[1].val()) {
// Do work
}
if (pwarr[0].val() == null || pwarr[0].val() == "" & pwarr[1].val() == null || pwarr[1].val() == "") {
// Do Work
}
});
You could use jquery in a similar fashion to check values on submit.
$('#formid').on('submit', function() { // Do work })
I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)
What I am trying to do is redirect to a new page if the "yes" button is clicked. I already have a prompt set up if they click "no". However, there is a form (name and email) that needs to be filled out for this to work. If they do not fill out these details, I want a prompt to arise telling the user that they need to fill them out before they can proceed.
I am fairly new to javascript so any tips or explanations would be greatly appreciated.
Below is the html code
<input type="radio" name="radio" id="yes"><strong>Yes, I agree.</strong>
<br>
<input type="radio" name="radio" id="no" checked="checked"><strong>No, I do not agree. </strong><br>
<br>
If you agree, please enter your full name and email address in the spaces below and press submit.
<br>
<form> Full Name:<input type="text" name="fullname"></form>
<br>
<form> Email Address:<input type="text" name="email"></form>
<br>
<br>
<form action="endPage.jsp" id="form">
<input type="submit" id="submit" value="Submit" name="submit" />
</form>
And the javascript code
var submitBtn = document.getElementById("submit");
var termsChk = document.getElementById("yes");
var formFrm = document.getElementById("emailField");
var formFrm = document.getElementById("nameField");
submitBtn.addEventListener("click", function() {
if (termsChk.checked === true && formFrm)
{
alert("Checked!");
formFrm.submit();
} else {
alert("Please Contact Spearhead Mining Corporation: projects#spearheadmining.com to discuss your options for project submittal!");
}
return false;
});
Use window.confirm() with the spcific message to user and use window.location() to redirect to the new url.
result = window.confirm("Message to user");
if(result) {
window.location = "new url";
} else {
//do the rest of logic
}
For a more specific answer it might help if you posted the code for yes and no buttons, as well as the HTML code for the form. That being said the way you would generally handle this is in the code for the yes button you run whatever client side validations you need to run, in this case checking if the name and email fields aren't empty, then displaying your error message instead of redirecting if everything is not valid.
For instance in your yes handler
if(document.getElementById('emailField').value == null || document.getElementById('namefield') == null){
/*error handling code goes here*/
return
}
else{
/*redirection code goes here*/
}