I am making a password validation using js and html. It suppose to show certain information under the input parts if the input is not valid. But whatever the input is, there's no message at all. I am not sure which part I did wrong. Code is posted below
var name = document.getElementById("userName");
var passWord = document.getElementById("passWord");
var flag;
function check() {
flag = validateInput(name, passWord);
if (flag)
isPaswordValid(passWord);
if (flag)
ispassWordStrong(passWord);
}
function validateInput(name, passWord) {
if (name.length = 0 || passWord.length < 0) {
document.getElementById("errorMessage").innerHTML = "Please enter Username and passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check Username and passWord are valid
function isPaswordValid(passWord) {
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
//Check passWord is valid or not and having length of passord should not less than 8
if (passWord.length < 8 || (!re.test(passWord))) {
document.getElementById("errorMessage").innerHTML = "Invalid passWord. Please enter new passWord";
return false;
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
return true;
}
}
//Check password has no more than 3 characters from username in passWord
function ispassWordStrong(userName, passWord) {
var n = 0;
for (var i = 0; i < userName.length; i++) {
if (passWord.indexOf(userName[i]) >= 0) {
n += 1;
}
}
if (n > 3) {
document.getElementById("errorMessage").innerHTML = "passWord can't contain more than 3 characters from the username.";
}
else {
document.getElementById("errorMessage").innerHTML = "Valid input";
}
}
});
<body>
<fieldset>
<legend>Password Validator</legend>
User Name:
<input type="text" id="userName" name="userName" placeholder="User Name" onkeyup='check();' /><br>
passWord:
<input type="password" id="passWord" name="passWord" placeholder="Password" onkeyup='check();' />
<input type="submit" id="inputValidate" value="Validate"><br /><br />
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
</body>
Sorry for the long codes and thanks for your help.
The following should do what you require:
// collect all DOM elements in object ti: ti.i, ti.e, ti.u, ti.p
const ti=["inputValidate","errorMessage","userName","passWord"]
.reduce((a,c)=>(a[c.substr(0,1)]=document.querySelector('#'+c),a),{});
// delegated event listening for event "input":
document.querySelector('fieldset').addEventListener('input',ev=>{
if (Object.values(ti).indexOf(ev.target)>1){ // for userName and passWord do ...
let u=ti.u.value.toLowerCase();
ti.e.textContent= (ti.p.value.length > 2
&& ti.p.value.split('').reduce((a,c)=>a+=u.indexOf(c.toLowerCase())>-1?1:0,0) > 2 )
? "The password contains at least 3 letters from the username!" : "";
}})
// event listening for button click on "validate":
ti.i.addEventListener('click',ev=>!(ti.e.textContent=
(ti.u.value.trim().length ? "" : "User name is empty.") ||
(ti.p.value.match(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/)
? "" : "The password is not complex enough!" )))
<fieldset>
<legend>Password Validator</legend>
User Name:<br/>
<input type="text" id="userName" name="userName" placeholder="User Name"/><br>
passWord:<br/>
<input type="password" id="passWord" name="passWord" placeholder="Password"/>
<input type="submit" id="inputValidate" value="Validate"><br/>
<b><span style="color:red;" id="errorMessage"></span></b>
</fieldset>
While inputting characters in the fields #userName and #passWord it checks for the occurence of user name characters in the password. This is done ignoring upper or lower case. And when clicking on the "validate" button the complexity of the password is checked against the regular expression /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/. This regular expression demands at least
one upper case chraracter,
one lower case character
one number and
a minimum length of 8.
There is also a rudimentary check on the user name. It must contain at least one non-blank character. The event handler for the click event on the "validate" button returns false whenever an error is detected. This can be used to prevent the submission of the form. However, the form itself was not supplied by OP.
Related
I have already a form verification in JS, that allows for an alert display in Front when one or several values are incorrect (eg. Password too short, needs at least one number).
I want to change these alerts to messages that will display in an HTML p above the affected input.
I have the following in HTML:
<form id="formNew">
<div>
<p id="msgPseudo"></p>
<label for="pseudo">Pseudo</label>
<br>
<input type="text" name="pseudo" id="pseudo" required>
</div>
<div>
<p id="msgEmail"></p>
<label for="email">Email</label>
<br>
<input type="email" name="email" id="email" minlength="8" maxlength="30" required>
</div>
<div>
<p id="msgPass"></p>
<label for="password">Password</label>
<br>
<input type="password" placeholder="*******" id="password" required>
</div>
<div>
<p id="msgPassRep"></p>
<label for="passwordRepeat">Confirm password</label>
<br>
<input type="password" placeholder="*******" id="confirm_password" required>
</div>
<div>
<input type="submit" name="submit" id="submit" value="Create an account">
</div>
</form>
and the following in JS:
function valideForm(e) {
e.preventDefault();
var valPseudo = document.getElementById("pseudo").value;
var valPassword = document.getElementById("password").value;
var valEmail = document.getElementById("email").value;
var errorsPass = [];
var errorsPseudo = [];
var emailRegex = /.+#.+\..+/;
let letters = 'abcdefghijklmnopqrstuvwxyz'
let numbers = '0123456789'
let letterCount = 0
let numberCount = 0
for (let character of valPseudo.toLowerCase()) {
if (letters.includes(character))
++letterCount
else if (numbers.includes(character))
++numberCount
else
return false //A non [a-zA-Z0-9] character was present
}
if (letterCount + numberCount > 40)
errorsPseudo.push("Pseudo is too long") //The name is too long
if (letterCount + numberCount < 5)
errorsPseudo.push("Pseudo is too short")//The name is too short
if (letterCount < 1)
errorsPseudo.push("Pseudo needs at least one letter") //There aren't enough [a-zA-Z] characters
if (numberCount < 1)
errorsPseudo.push("Pseudo needs at least one number") //There aren't enough [0-9] characters
if (errorsPseudo.length) {
alert(errorsPseudo);
}
if(emailRegex.test(valEmail) == false) {
alert ("veuillez entrer un E-mail valide");
return false;
}
if (!valPassword) {
alert("Password is empty");
}
if((valPassword.length < 8)) {
errorsPass.push("Password should be at least 8 characters")
}
if((valPassword.length > 30)) {
errorsPass.push("Password should not exceed 30 characters")
}
if (!/[A-Z]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 uppercase")
}
if (!/[a-z]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 lowercase")
}
if (!/[0-9]/.test(valPassword)) {
errorsPass.push("Password should have at least 1 number")
}
if (!/(?=.[$#%£&§#])/.test(valPassword)) {
errorsPass.push("Password should have at least 1 special character")
}
if (errorsPass.length) {
alert(errorsPass);
}
var password = document.getElementById("password");
var confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("passwords aren't the same");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
}
document.getElementsByTagName('form')[0].addEventListener('submit', valideForm);
I want to change the alerts display in Pseudo, Email and Password tests, as well as the .setCustomValidity for Password confirmation...
TO messages that will appear in HTML Front at the <p></p> location above each corresponding input.
Is it possible?
You can add a prompt text after the input box, such as the < p > tag. When the input content changes (such as
$("# password"). change (function () {$("P"). text)("messages ")})
)
here is my working code on password field validation check. it works fine while all criterion are met but when it doesn't it gets stuck on last validation checks in case of submitting form after validation completions!!
Please have a look [here][1]
[1]: https://codepen.io/bappyasif/pen/vYNoEap?editors=1112
var firstPasswordInput = document.querySelector("#first");
var secondPasswordInput = document.querySelector("#second");
var submit = document.querySelector("#submit");
let symbolPattern = /[\!\#\#\$\%\^\&\*]/g;
let numberPattern = /\d/g;
let lowercasePattern = /[a-z]/g;
let uppercasePattern = /[A-Z]/g;
let unallowedCharacters = /[^A-z0-9\!\#\#\$\%\^\&\*]/g;
submit.onclick = function () {
let firstPassword = firstPasswordInput.value;
let secondPassword = secondPasswordInput.value;
if (firstPassword === secondPassword && firstPassword.length > 0) {
checkRequirements();
} else {
secondPasswordInput.setCustomValidity("Passwords must match!");
}
function checkRequirements() {
if (firstPassword.length < 6) {
firstPasswordInput.setCustomValidity("Fewer than 6 characters");
// return;
} else if (firstPassword.length >= 10) {
firstPasswordInput.setCustomValidity("greater than 10 characters");
// return;
}
// Pattern Checks
if (!firstPassword.match(symbolPattern)) {
firstPasswordInput.setCustomValidity(
"missing a symbol (!, #, #, $, %, ^, &, *"
);
if (!firstPassword.match(numberPattern)) {
firstPasswordInput.setCustomValidity("missing a number");
// return false;
// return;
}
if (!firstPassword.match(lowercasePattern)) {
firstPasswordInput.setCustomValidity("missing a lowercase letter");
// return;
}
if (!firstPassword.match(uppercasePattern)) {
firstPasswordInput.setCustomValidity("missing an uppercase letter");
// return;
}
if (firstPassword.match(unallowedCharacters)) {
firstPasswordInput.setCustomValidity("includes illegal character: ");
// return;
}
}
}
};
Form Related HTML Tags For Shared Code Snippet:
<label>
<input id="first" type="password" placeholder="New password" autofocus maxlength="100" required />
</label>
<!-- type="password" -->
<label>
<input id="second" type="password" placeholder="Repeat password" autofocus maxlength="100" required />
</label>
<input id="submit" type="submit" />
My javascript isn't running when I click submit on my form page.
<form onsubmit="validateReg()">
<p>
//email registration
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
//password registration
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</for
I've tried multiple times linking the Javascript to the Html form and on the page when I click submit it doesn't return any of my error alerts.
//HTML
<form onsubmit="validateReg()">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p><p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br>
<input type="submit" class="submit">
</form>
//Javascript
//Main Function
function validateReg(){
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.value.match(lowerCaseLetters)) {
return true;
}else{
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.value.match(upperCaseLetters)){
return true;
}else{
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.value.match(numbers)){
return true;
}else{
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.value.match(special)){
return true;
}else{
alert("Password needs a special character!");
return false;
}
if(password.value.length >=8){
return true;
}else{ alert("Password needs to be at least 8 characters");
return false;
}
}
I expect the code to output errors when a password is incorrectly submitted and when a password and email is correctly submitted so out put thank you.
As Oluwafemi put it you could put an event listener on your 'submit' event instead. I would put the event on the submit button though. That way you can stop it on the click event without having to fire the submit of the form. If you update your code it could help with troubleshooting in the future.
It wouldn't take much to modify your code either.
First, you would need to update your form to look like this:
<form id="form">
<p>
<input type="text" id="e-mail" placeholder="Email" />
</p>
<p>
<input type="text" id="pswd" placeholder="Password" />
</p>
<br />
<input id="submitButton" type="submit" class="submit">
</form>
Then add this below your javascript function like so:
document.querySelector("#submitButton").addEventListener("click", function(event) {
event.preventDefault;
validateReg()
}, false);
What this is doing is stopping the submit of the form and doing the check as expected. You can read more on this on the Mozilla developer site.
You will need to add document.getElementById('form').submit(); to any return statement that was set to true.
I did however, update the code to have the submit become the default functionality and the checks just return false if they fail like this:
//Javascript
//Main Function
function validateReg() {
var email = document.getElementById('e-mail').value;
var password = document.getElementById('pswd').value;
var emailRGEX = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var emailResult = emailRGEX.test(email);
//validate Email
if(emailResult == false){
alert("Please enter a valid email address");
return false;
}
//validate lower case
var lowerCaseLetters = /[a-z]/g;
if(password.match(lowerCaseLetters) == null) {
alert("Password needs a lower case!");
return false;
}
//validate upper case
var upperCaseLetters = /[A-Z]/g;
if(password.match(upperCaseLetters) == null){
alert("Password needs an upper case!");
return false;
}
//validate numbers
var numbers = /[0-9]/g;
if(password.match(numbers) == null){
alert("Password needs a number!");
return false;
}
//validate special characters
var special = /[!##$%^&*(),.?":{}|<>]/g;
if(password.match(special) == null){
alert("Password needs a special character!");
return false;
}
if(password.length < 8){
return false;
}
document.getElementById('form').submit();
}
A better way to do this is to add an event listener to your js file and listen for the 'submit' event. Followed by your function.
Furthermore ensure that your js file is added to your script tag in your HTML file. That should work if your logic is correct.
I want to use javascript to validate my form's input before sending the data to the php file. I tried using onSubmit, but for some reason the javascript function is getting skipped over and the data is going straight to the php file. I'm not sure what's wrong with my code- I'd initially put the javascript in another file, then I included it in the page itself with a <script> tag, it's still not working. Here's my code-
The form-
<form action="includes/register.inc.php" name="registration_form" method="post" onSubmit="return regform(this.form,
this.form.first-name, this.form.last-name, this.form.signup-username, this.form.signup-email,
this.form.signup-password, this.form.confirm-password);">
<input id="first-name" name="first-name" type="text" placeholder="First Name"/>
<input id="last-name" name="last-name" type="text" placeholder="Last Name"/>
<input id="signup-username" name="signup-username" type="text" placeholder="Username"/>
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail"/>
<input id="signup-password" name="signup-password" type="password" placeholder="Password"/>
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password"/>
<input type="submit" value="CREATE ACCOUNT"/>
</form>
Javascript-
function regform(form, fname, lname, uid, email, password, conf) {
// Check each field has a value
if (uid.value == '' ||
email.value == '' ||
password.value == '' ||
fname.value == '' ||
lname.value == '' ||
conf.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if(!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if(!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
it's not this.form, since this already refers to the form. also you need to use brackets for any properties that contain a hyphen as JS will think it's a minus sign. this['last-name']
Try this. Instead of pass a bunch of params to the function, I'm passing the form itself, then pulling out values from there.
function regform(form) {
// Check each field has a value
if (form['signup-username'].value == '' ||
form['signup-email'].value == '' ||
form['signup-password'].value == '' ||
form['first-name'].value == '' ||
form['last-name'].value == '' ||
form['confirm-password'].value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the username
re = /^\w+$/;
if (!re.test(uid.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
return false;
}
var alphaExp = /^[a-zA-Z\-]+$/;
if (!fname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
if (!lname.value.match(alphaExp)) {
alert("First name must contain only letters and hyphens. Please try again");
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != conf.value) {
alert('Your password and confirmation do not match. Please try again');
return false;
}
// Finally submit the form.
return true;
}
<form action="" name="registration_form" method="post" onSubmit="return regform(this);">
<input id="first-name" name="first-name" type="text" placeholder="First Name" />
<input id="last-name" name="last-name" type="text" placeholder="Last Name" />
<input id="signup-username" name="signup-username" type="text" placeholder="Username" />
<input id="signup-email" name="signup-email" type="email" placeholder="E-mail" />
<input id="signup-password" name="signup-password" type="password" placeholder="Password" />
<input id="confirm-password" type="password" name="confirm-password" placeholder="Confirm Password" />
<input type="submit" value="CREATE ACCOUNT" />
</form>
I am trying to create a very very basic profile page using Name, Email, Username, and Password. I have to have a password validation code/button.
The home page will be very similar to a common profile page. The user must be able to input the following:
Name field
Email field
User ID field
Password field 3
Validation Password field
The following buttons are required:
Password validation button
Create Profile button
I can put it all together, but the problem I am having is that the javascript console is telling me that there are some errors in the code...
function validate(){
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('Password2');
if (pass1 == pass2)
{
alert("Passwords Match")
}
else
{
alert("Passwords Do Not Match")
}
}
<head>
<script type="text/javascript" src="Profile Page.js"></script>
</head>
<body>
Enter First and Last Name
<input type="text" id="name">
<br>Enter Your Email Address
<input type="text" id="email">
<br>Please Enter a Username
<input type="text" id="username">
<br>Please Enter a Password
<input type="password" id="password">
<br>Enter Your Password Again
<input type="Password" id="password2">
<br>
<button type="button" id="validate" onClick="validate()">Validate Password</button>
<button type="button" id="create" onClick="submit()">Create Profile</button>
</body>
Ok, so I figured out where my errors were, now the alert that I set up for the passwords not matching is coming up, even when the passwords are the same thing. Any suggestions?
Please try it like this:
function validateForm(){
var pass1 = document.getElementsByName("password")[0].value;
var pass2 = document.getElementsByName("password2")[0].value;
if (pass1 === pass2) {
alert("Passwords Match");
} else {
alert("Passwords Do Not Match");
}
}
Enter First and Last Name
<input type = "text" id = "name" /><br/>
Enter Your Email Address
<input type = "text" id = "email" /><br/>
Please Enter a Username
<input type = "text" id = "username" /><br/>
Please Enter a Password
<input type = "password" name = "password" /><br/>
Enter Your Password Again
<input type = "Password" name= "password2" /><br/>
<button type = "button" id = "validate" onclick = "validateForm();">Validate Password</button>
<button type = "button" id = "create" onclick = "submit()">Create Profile</button>
Below is the generic function to validate password by comparing with repeat password, Contains lowercase, Contains uppercase, Contains digit
function validatePassword(password, repeatPassword){
var MinLength = 6;
var MaxLength = 15;
var meetsLengthRequirements:boolean = password.length >= MinLength && repeatPassword.length <= MaxLength;
var hasUpperCasevarter:boolean = false;
var hasLowerCasevarter:boolean = false;
var hasDecimalDigit:boolean = false;
if (meetsLengthRequirements)
{
for (var i = 0, len = password.length; i < len; i++) {
var char = password.charAt(i);
if (!isNaN( +char * 1)){
hasDecimalDigit = true;
}
else{
if (char == char.toUpperCase()) {
hasUpperCasevarter = true;
}
if (char == char.toLowerCase()){
hasLowerCasevarter = true;
}
}
}
}
var isValid = meetsLengthRequirements
&& hasUpperCasevarter
&& hasLowerCasevarter
&& hasDecimalDigit;
return isValid;
}