javascript validation of username and password - javascript

I am working on a homework assignment and have been wracking my brain trying to figure out how to do the following:
uName -
requires something to be entered (if not throws error),
requires alphanumeric with at least one letter and one character (if not throws error),
otherwise passes checks and increments the checkev counter
password -
requires something to be entered (if not throws an error), requires the character count to be greater than or equal to 8 characters (if not throws an error), otherwise passes checks and increments the checkev counter
At this point, I have the original errors that are triggered by no entry, however, once I test the second case of not meeting alphanumerics or 8 characters I do not get the expected response.
Below is an example of the JS I have written thus far as well as the HTML:
Any help would be largely appreciated! Thank you in advance!
window.onload = init;
function checkRegistration() {
var checkev = 0;
var uName = document.pageForm.userName.value;
var alphaNum = /^[a-z0-9]+$/i;
var password = document.pageForm.password.value;
if (uName == "") {
document.getElementById('userName').innerHTML = "A username is required.";
checkev=0;
} else if (uName.match != alphaNum)
document.getElementById('userName').innerHTML = "Username must contain at least one letter and one number, no special characters.";
{
document.getElementById('userName').innerHTML = "";
checkev++;
}
if (password == "") {
document.getElementById('password').innerHTML = "A password is required.";
checkev = 0;
} else if (password.lenth >= 8)
document.getElementById('password').innerHTML = "A password of at least 8 characters is required.";
else {
document.getElementById('password').innerHTML = "";
checkev++;
}
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script src="js/registration.js"></script>
</head>
<form name="pageForm">
<form action="#">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span class="error" id="userName"></span><br><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span class="error" id="password"></span><br><br>
<input type="button" value="Submit" onclick="checkRegistration()">
</form>
</form>

1 typo and 1 logic issue.
Try password.length < 8

<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<input type="password" name="password" id="password" placeholder="Enter your Password" />
you miss id attribute when you used getElementById()
and good luck...

Do not hard code your validation simply use V4F
Check out https://v4f.js.org for more details
import {Field, Schema} from "v4f";
export Schema({
username: Field()
.alpha()
.min(1)
.required(),
password: Field()
.min(8)
.required()
});

Related

How to enable/disable a button dynamically with JavaScript, based on conditions with textfields

I have the following jsp page, consisting of 2 text fields, 2 password fields, 1 email field and 1 file-uploader, followed by a disabled button:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
My purpose is to enable and disable the button at run time using pure JavaScript, based on 2 conditions:
All the text fields, except the file-uploader, must all be filled in;
The password fields must match.
So I wrote the following JavaScript code:
RegScript.js
name = document.getElementById("name");
lastname = document.getElementById("lastname ");
email = document.getElementById("email");
password = document.getElementById("password");
confirmpassword = document.getElementById("confirmpassword");
register = document.getElementById("register");
//password matching & text fields checking
confirmpassword.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
password.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
The following script seems to work partially, but it has some errors: When I fill in all the text fields in order as they appear, in the moment that the passwords match the button is enabled, as well as if I delete the password it's disabled again, but if instead I delete one of the other three text fields (name, lastname or email) the button remains enabled, when it should not. What can I do to simplify the code (I'm not satisfied with the way I wrote my code, since it's redundant) and to solve to this issue?
You can DRY the validation logic in a validate function that runs whenever inputs change, which is set up using addEventListener on each of them.
This unifies the logic and makes it easy to extend later, for example you might check the emails .validity.valid property to see if it's an actual email.
This is a working snippet:
let name = document.getElementById("name");
let lastname = document.getElementById("lastname");
let email = document.getElementById("email");
let password = document.getElementById("password");
let confirmpassword = document.getElementById("confirmpassword");
let register = document.getElementById("register");
[name, lastname, email, password, confirmpassword].forEach(input => {
input.addEventListener("input", validate)
})
const hasLength = input => input.value.trim().length > 0;
function validate() {
let isValid =
hasLength(name) &&
hasLength(lastname) &&
hasLength(email) &&
hasLength(password) &&
password.value == confirmpassword.value;
console.log(isValid)
register.disabled = !isValid;
}
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>

Validating User Inputs Using Javascript

I am making a page that validates user inputs. The username should be in an email format and the password should be 7 or more characters. I think I have the code down, but am struggling to connect the javascript so that it works properly and validates the user inputs.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<br><br>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<br><br>
<button type="submit" class="signinbtn">Sign In</button>
</form>
function validateForm() {
let regexEmail = / ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (
password.length >= 7 || username.match(regexEmail)
) {
alert("Welcome");
return true;
}
else {
alert("error, username must be in email format & password must be 7 or more characters");
return false;
}
</body>
</html>
you are missing a bunch of script tags and the JS needs to be refactored with some minor changes.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form>
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
id="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
id="password"
required
/>
<br /><br />
<button type="submit" id="btn" class="signinbtn">Sign In</button>
</form>
<script type="text/javascript">
let regexEmail =
/ ^ \ w +([\.-] ? \ w +) * # \ w +([\.-] ? \ w +) *(\.\ w { 2, 3 }) + $ /;
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
document.getElementById("btn").addEventListener("click", (e) => {
e.preventDefault();
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
}
});
</script>
</body>
</html>
There's a couple of issues I can see here, first of all your JavaScript isn't within <script></script> tags.
Second, the validateForm function you have written isn't attached to your form HTML. Take a look here to see how you can run a function when your form is submitted:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Edit: Here's the list of issues:
Your form doesn't have an id attribute but you refer to myForm in your function
Your JavaScript needs to be wrapped in <script> tags
Your regex has spaces in which will prevent it from matching
You're missing a closing curly bracket at the end of your function
You're not attaching the function to your form so it won't be called when it is submitted (as per the link I posted).
Here's the fixed code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="assignment.css" />
</head>
<body>
<form id="myForm">
<h1>Sign in</h1>
<label for="username"><b>Username</b></label>
<input
type="text"
placeholder="Enter Username"
name="username"
required
/>
<br /><br />
<label for="password"><b>Password</b></label>
<input
type="password"
placeholder="Enter Password"
name="password"
required
/>
<br /><br />
<button type="submit" class="signinbtn">Sign In</button>
</form>
<script>
function validateForm() {
let regexEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
if (password.length >= 7 || username.match(regexEmail)) {
alert("Welcome");
return true;
} else {
alert(
"error, username must be in email format & password must be 7 or more characters"
);
return false;
}
}
const formEle = document.getElementById("myForm");
formEle.addEventListener("submit", validateForm);
</script>
</body>
</html>
Re:your comment - you have a function and you have an HTML form. In the original code, where is your function called? What triggers the validation on the form fields to be run? In the code I've provided I've attached your function to the submit event of the form so when the form is submitted, your function is called. There's other ways this could be handled - adding a click handler on the button, adding a change handler to the form fields, etc. etc.

Why is my HTML file unable to use the JavaScript file that I have linked?

JavaScript file is not used in the HTML file despite linking it
I am unable to use the JavaScript file and validate my HTML form. I am wondering if the issue is the linking of the src directory is wrong or could it be that I am missing something in my JavaScript code.
<html>
<head>
<title>Registration Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/validation.js" type="text/javascript">
</script>
</head>
<body>
<form action="validate" method="post" name="register">
Full Name: <input type="text" name="name" required/><br/> Email Address: <input type="email" name="email" required/><br/> Address Line 1: <input type="text" name="address1" required/><br/> Address Line 2: <input type="text" name="address2" /><br/> Postal Code: <input type="number" name="postal" required/><br/> Mobile Number: <input type="number" name="mobile" required/><br/> Password: <input type="password" name="password" required/><br/> Confirm Password: <input type="password" name="cfpassword"
required/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
function validateForm() {
//Use a regular expression to check for the pattern of the password
var regexPass = "^[0-9]{6}[a-zA-Z]{1}$";
var regexMobile = "^[0-9]{8}$";
var regexPost = "^[0-9]{6}$";
//Retrieve the VALUE from the "password" field found in the "register" form
var password1 = document.forms["register"]["password"].value;
var password2 = document.forms["register"]["cfpassword"].value;
var postalcode = document.forms["register"]["postal"].value;
if (matchPost === null) {
alert("The postal code given in the correct format. Please ensure
that is contains exactly 6 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
if (matchMobile === null) {
alert("The mobile number given in the correct format. Please ensure
that is contains exactly 8 digits.
");
// Return false to tell the form NOT to proceed to the servlet
return false;
}
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
return true
}
}
If your JS folder is in the same directory as your html file this code should work. Write a simple alert('ahoy') function in your JS file and reload your html to verify if your JS file is loaded or not.

JS/HTML onblur runs only once

I'm having an issue with a college assignment regarding data validation using JS. I have set the fields to trigger validation onblur and everything works except my code for making sure the password and password verification works. Once the verification function goes to != it appears the onblur doesn't run again when the field is exited.
I have extracted the code here. Can anyone tell me what I have done wrong?
function PVVal() {
var pwTest = document.getElementsByName("password")[0].value;
var pwVerify = document.getElementsByName("passwordVerify")[0].value;
//trim whitespace
pwTest = pwTest.trim();
pwVerify = pwVerify.trim();
if (pwTest != pwVerify) {
document.getElementById("PVMsg").innerHTML = "<font color='red'>Passwords do not match</font>";
PVCheck = 0;
} else {
document.getElementbyId("PVMsg").innerHTML = "";
PVCheck = 1;
}
}
<label for="Password">Password: <span id="PWMsg"></span>
</label>
<input type="password" name="password" placeholder="Enter your Password" onblur="PWVal()" />
<label for="passwordVerify">Verify your Password: <span id="PVMsg"></span>
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" onBlur="PVVal()" />
I found 4 typos around the naming of PWVal, getElementById and onblur. After fixing those typos, the snippet appears to work as shown below. The validation works properly when exiting the field.
Additionally, it's worth noting to check the console first when experiencing errors like this in the future. The incorrect function names will be called out there and start you down the right path for troubleshooting.
function PWVal() {
var pwTest = document.getElementsByName("password")[0].value;
var pwVerify = document.getElementsByName("passwordVerify")[0].value;
//trim whitespace
pwTest = pwTest.trim();
pwVerify = pwVerify.trim();
if (pwTest != pwVerify) {
document.getElementById("PVMsg").innerHTML = "<font color='red'>Passwords do not match</font>";
PVCheck = 0;
} else {
document.getElementById("PVMsg").innerHTML = "";
PVCheck = 1;
}
}
<label for="Password">Password: <span id="PWMsg"></span>
</label>
<input type="password" name="password" placeholder="Enter your Password" onblur="PWVal()" />
<label for="passwordVerify">Verify your Password: <span id="PVMsg"></span>
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" onblur="PWVal()" />
It was PVMsg. I don't knwo why but I changed the span id="theMess" and everything started working as intended.
Thank you for the assistance.

How to setCustomValidity when username is less than 4 characters?

I have this simple html and Jquery code. I want to set the setCustomValidity to appear when user inputs 4 characters in the textfield. So far I'm not getting such result in my code:
<html>
<body>
<input type="text" placeholder="Username" oninvalid="setCustomValidity('Please enter username')" oninput="setCustomValidity('')" id="username" name="username"" required>
</body>
<script>
var username = $("#username").val();
if (username.strlen < 4) {
username.setCustomValidity('Username must contain at least 5 characters');
} else {
username.setCustomValidity('');
}
$(document).ready(function() {
$("#username").keyup(checkUsername);
});
</script>
</html>
I tried this:
<script>
var username = $("#username").val();
if (username.strlen < 4) {
username.setCustomValidity('Username must contain at least 5 characters');
} else {
username.setCustomValidity('');
}
$(document).ready(function() {
$("#username").keyup(checkUsername);
});
</script>
But it doesn't work. Can anyone help?
friend why you are not using html5 pattern like
<input type="text" placeholder="Username" pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">
Note : Now user cant able to enter less than 5 character in user text field
Demo:-
<!DOCTYPE html>
<html>
<body>
<form action="youractionpage.php">
<input type="text" placeholder="Username" pattern=".{5,}" title="Username must contain at least 5 characters" required id="username" name="username">
<input type="submit" value="ok">
</form>
</body>
</html>
There's no such thing as strlen method in string. You may want to use length.
Sooo it should be....
if (username.length <= 4)
I'm not sure if its <= or = for your message is contradicting with your title. I mean this one. Username must contain at least 5 characters but title is username is less than 4 characters.

Categories