Form only validates one field with javascript - javascript

I'm trying to make a simple register form that makes sure the username and password have been entered correctly before submitting. Here's my form:
<form id="register" name="register" action="" method="POST" onsubmit="return validate_account_creation(this)">
<label> Username
<input type="text" name="username" />
</label>
<label> Password
<input type="text" name="password" />
</label>
<input type="submit" name="submit" value="Submit" class="button"/>
</form>
And here are my javascript functions:
function validate_username(username) {
var regex = /[a-zA-Z0-9\-\_]{5,15}/g;
var str = username;
if (!regex.test(str)) {
alert("Your username must be between 5 and 15 characters in length");
register.username.focus();
return false;
}
}
function validate_password(password) {
regex = /[a-zA-Z]{5,}[0-9]{1,}/g;
str = password;
if (!regex.test(str)) {
alert("Your password must be at least 6 characters in length and must contain at least 1 number");
register.password.focus();
return false;
}
}
//Validate register form
function validate_account_creation(form) {
return validate_username(form.username.value);
return validate_password(form.password.value);
return true;
}
The username function works fine and it validates that one every time. However, if the username is correct, the form submits. The second function never activates. If the first function doesn't return anything, shouldn't the second function then be called and validate the second field?

It's the return statements. A return aborts the rest of the function and returns the result, so your validation should look like:
Javascript
function validate_account_creation(form) {
var username = validate_username(form.username.value);
var password = validate_password(form.password.value);
return username && password; // if both are true, submit form
}

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

Javascript form validation not loading PHP page

I have the following form in a PHP page
<form action="login.php" method="post">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<input type="button" name="loginSubmit" value="submit" onclick="return validateLogin()">
</form>
My validation looks like this
function validateLogin() {
var school = document.getElementsByName("schoolInput")[0].value
var username = document.getElementsByName("usernameInput")[0].value
var password = document.getElementsByName("passwordInput")[0].value
var failed = false;
if(!school){
document.getElementById("erschool").innerHTML = "No school entered";
failed = true;
}
if(!username){
document.getElementById("eruser").innerHTML = "No username entered";
failed = true;
}
if(!password){
document.getElementById("erpass").innerHTML = "No password entered";
failed = true;
}
if(failed){
return failed;
}
return true;
}
The JS in the validation works as it activates the error messages. However, if the form is completed correctly, it doesn't load login.php as it should.
I'm running the app on Heroku for testing.
What am I doing wrong?
You need to use <button type=submit"> to submit the form. Also, you can move the validation into the form. i.e.:
<form action="login.php" method="post" onclick="return validateLogin()">
School: <input type="text" name="schoolInput"><div id="erschool"></div><br>
Username: <input type="text" name="usernameInput"><div id="eruser"></div><br>
Password: <input type="text" name="passwordInput"><div id="erpass"></div>
<button type="submit" name="loginSubmit" value="submit">
</form>
Also, your validation function is wrong - it will always return true (so the form will always be submitted):
if(failed){
return failed; // if failed is true, then return TRUE...
}
return true; // ....otherwise return TRUE!!
I presume you mean to return !failed so if failed is true then you return false?
You don't actually need to check the value for failed either- you can just return !failed:
if failed is true, then !failed will return false so the form is not submitted
if failed is false, then !failed will return true so the form is submitted
How to make it work
What you probably wanted to achieve is:
<button type="button" onclick="if(validateLogin()) this.form.submit()">
This way, your form only gets submitted if the function returns TRUE. (Which, as #FluffyKitten pointed out, will always be the case so you have to fix the validation function too.)
There are more than one ways to validate a form. My favorite is giving the form an onsubmit handler, and the syntax you used on the button looks like you were trying to mix this technique with the button-click validation method. Form onsubmit way looks like this:
<form onsubmit="return validateLogin()">
...
...
<button type="submit">
</form>
These are 2 separate ways.
Method 1: form onsubmit=return valid() + button type=submit
Method 2: form + button type=button onclick=if(valid()) submit()
Improve validateLogin
I'd suggest some refactoring here, both for readability and ease of use.
function validateLogin() {
var checkEmpty = function(name) {
var element = document.getElementsByName(name+"Input")[0];
if(element.value !== "") return false; // return if not empty
var errorField = document.getElementById("er"+name);
errorField.innerHTML = "No value for "+name;
return true;
}
if(checkEmpty("school" )) return false;
if(checkEmpty("username" )) return false;
if(checkEmpty("password" )) return false;
return true;
}

JS Student Email Validation

I am a beginner in Javascript and am looking to find a solution to why the code below is not working.
I've reviewed several tutorials here on StackOverflow and believe it should work... but it's not.
The HTML looks like this:
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
<br>
</form>
<input type="button" onclick = "validateEmail()">
The Javascript looks like this:
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms[personalInfo].elements[Email].value;
if (reg.test(address) == false) {
alert ("Email not valid");
return false;
}
return true;
}
By my accounts, this should pop up an alert if the email address entered by the user is not valid.
Instead, nothing happens at all. I'm not sure if the test is even run.
function validateEmail() {
// There are, I feel, better version of this regex online
// You can check "https://emailregex.com/"
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
// document.getElementById() - Easier to read & understand, and more widely used
var address = document.getElementById('Email').value;
// Corrected your returns - not the main issue in the function, but the old
// returns might have caused confusion
if (reg.test(address) == false) {
alert("Email not valid");
return false
}
return true
}
<form id="personalInfo">
<h2>Email: </h2>
<input type="text" name="Email" id="Email">
</form>
<!-- You had a typo on the onclick but has since been fixed -->
<input type="button" onclick="validateEmail()" value="Submit">
Two issues here:
1- In your HTML, you are missing an = sign here: onclick"validateEmail()" (Edit: seems you fixed it now)
2- in your Javascript, the indices personalInfo and Email are strings, wrap them in quotation marks:
var address = document.forms['personalInfo'].elements['Email'].value;
function validateEmail()
{
var reg = /^([A-Za-z0-9_\-\.]){1,}\#([A-Za-z0-9_\-\.]){1,}\.([A-Za-z]{2,4})$/;
var address = document.forms['personalInfo'].elements['Email'].value;
if (reg.test(address)== false)
{
alert ("Email not valid");
return false
}
return true;
}
<form id="personalInfo">
<h2>Email: </h2> <input type="text" name="Email" id="Email"> <br>
</form>
<input type="button" onclick="validateEmail()">
When dealing with email inputs, set the input type to email instead of text - like so:
<input name="my-email" type="email" />"
Then the browser will perform validation on the input; such as if the input doesn't have the # present.

Use JavaScript to change the href Tag depending on input field

I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>

Unable to stop form from submitting when validating an email

I am making a simple form that takes the value from a text input, checks if all the characters that are in an email address are there and returns true or false. According to a lot of different resources, if it returns false, then the form shouldn't be submitted. However, when I test it in JS bin, it submits it. Here's the code:
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
console.log(re.test(email));
}
<form name="myForm" onsubmit="return validateEmail(this)">
<input name="myText" type="text">
<input type="submit" value="Submit">
</form>
you need to return false if the validation fails, so simply replace
console.log(re.test(email));
with
return re.test(email);
Demo
Try this:
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Change <form name="myForm" onsubmit="return validateEmail(this)">
With this <form name="myForm" onClick="return validateEmail(this)">
And function is like this
function validateEmail(x) {
console.log(x);
var email = x.myText.value;
console.log(email);
var re = your regular expression;
if((re.test(email)){
document.getElementById(myForm).submit();
}

Categories

Resources