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.
Related
I have been working on a little coding project for my friends. This includes a somewhat password system that changes your username. I implemented this so that impersonation was harder to do.
<main class="join-main">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Enter password..." required />
<button type="button" onclick="fn1()">Check ig</button>
<script>
function fn1() {
let pswvalue = document.getElementById("password").value
if (pswvalue = "1234") {
document.getElementById("username").value = "Hello"
} else {
return;
}
}
</script>
<form action="chat.html">
<div class="form-control">
<label for="username">Logging Into:</label>
<input
type="text"
name="username"
id="username"
placeholder="The User you are logging into will appear here."
readonly
/>
</div>
</form>
For some reason, even if the password isn't "1234", The username still changes to Hello. Any suggestions on how to fix it?
It should be if (pswvalue === "1234") since we are comparing two stings.
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()
});
I'm attempting to send an error message when either the email field or the phone field of a form doesn't match the regex. The validation message shouldn't submit if either fields are filled in.
What happens right now when I go to submit the form with one of the fields filled in with the proper information the form gives me the error message and will not post the form. Once I enter the correct input into the other field it processes the form.
What I want it to do is to process the form if either the email field is filled out or the phone field is filled out with information that matches the regular expressions.
If neither of the forms are filled out correctly I want the form to throw the error message.
Here's the if statement I am working with so far.
<form id="contact_form" action="" method="POST">
<input type=hidden name="" value="">
<input type=hidden name="" value="">
<p class="errmsg" id="name_errormsg"></p>
<input id="name" maxlength="80" name="form_name" placeholder="Name" size="20" type="text" />
<input id="email" maxlength="80" name="email" placeholder="Email" size="20" type="text" />
<input id="phone" maxlength="40" name="phone" placeholder="Phone number" size="20" type="text" />
<textarea id="description" name="description" placeholder="How can we help you?"></textarea>
<input type="submit" name="submit" value="Send message">
</form>
$(document).ready(function() {
$overlay = $(".modal-overlay");
$modal = $(".modal-frame");
$modal.bind('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e){
if($modal.hasClass('state-leave')) {
$modal.removeClass('state-leave');
}
});
$('.form-close-button').on('click', function(){
$overlay.removeClass('state-show');
$modal.removeClass('state-appear').addClass('state-leave');
});
$('#contactformbtn').on('click', function(){
$overlay.addClass('state-show');
$modal.removeClass('state-leave').addClass('state-appear');
});
var formHandle = document.forms[0];
formHandle.onsubmit = processForm;
function processForm(){
var emailInput = document.getElementById('email');
var emailValue = emailInput.value;
var phoneInput = document.getElementById('phone');
var phoneValue = phoneInput.value;
var regexPhone = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
var regexEmail = /^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if((!regexPhone.test(phoneValue)) ||(!regexEmail.test(emailValue))) {
nameErr = document.getElementById("name_errormsg");
nameErr.innerHTML = "Please enter your phone number or a valid email address.";
nameErr.style.color = "red";
return false;
}
}
});
If any of you could point out where I went wrong this that would be great!
Thank you for taking the time to read this.
Have a good day.
Based on your last comment (which should be in the question) your logic is wrong.
You're currently checking for failure of either field. If phone fails or email fails. If one field isn't filled in it'll fail because you don't allow blank.
You want to test for failure of both fields (with a caveat):
if (!regexPhone.test(phoneValue) && !regexEmail.test(emailValue)) {
....
Or you can change your regex.
The caveat is that say a user enters in a valid phone, but an invalid email: what should happen in that case? Should validation pass or fail?
So I have a simple HTML form for users to enter username and passwords and I'm validating that the passwords match using JavaScript. However for some reason I can't get the span to display whether or not the passwords match.
window.onload = init;
function init(){
function passMatch(){
console.log("Matching words.");
var pwd1 = document.getElementById("pwd1").value;
var pwd2 = document.getElementById("pwd2").value;
var output1 = document.getElementById("pwd1Hint");
var output2 = document.getElementById("pwd2Hint");
if (pwd1 === pwd2){
output1.innerHTML = "Yes!";
console.log(output1.textContent);
} else {
output1.innerHTML = "No!";
console.log(output1.textContent);
}
}
// event handlers
document.getElementById("pwd1").onchange = passMatch;
document.getElementById("pwd2").onchange = passMatch;
}
And here is the relevant HTML...
<fieldset name="LoginInfo"><input size="30" placeholder="username"
name="username" id="username" type="text"> <br>
<br>
Password:<br>
<input size="30" required="required" placeholder="password" name="pwd1"
id="pwd1" type="password"> <span class="hint" id="pwd1Hint">Password
is too short (must be at least 8 characters)</span> <br>
Repeat Password:<br>
<input size="30" required="required" placeholder="password" name="pwd2"
id="pwd2" type="password"> <span class="hint" id="pwd2Hint">Passwords
don't match</span><br>
I'm going to stab at this with limited information, but you said something very interesting to me:
I can't even get the span to display its default text of "Password is
too short (must be at least 8 characters)" when the page loads
But our Fiddle's are working for you. This is static text independent of JavaScript. That tells me that you might have CSS that we are not seeing which is hiding your span.
My guess is that your init function is never being called. Try just calling that function below the definition - so just define it and then below it add init(). That works in this fiddle:
https://jsfiddle.net/awt3dxdj/
Then you can just make it an anonymous function that is executed immediately (IIFE).
I want to check that two passwords are the same using Dojo.
Here is the HTML I have:
<form id="form" action="." dojoType="dijit.form.Form" />
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="This password doesn't match your first password" /></p>
<div dojoType="dijit.form.Button" onClick="onSave">Save</div>
</form>
Here is the JavaScript I have so far:
var onSave = function() {
if(dijit.byId('form').validate()) { alert('Good form'); }
else { alert('Bad form'); }
}
Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.
This will get you a lot closer
setting intermediateChanges=false keeps the validator running at every keystroke.
the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry
dijit.form.Form automatically calls isValid() on all its child dijits when it's submitted, and cancels submittion if they don't all validate. I though the invalid ones would get their error message, but they don't. That's left as an exercise for the reader ;-)
the validation function:
function confirmPassword(value, constraints)
{
var isValid = false;
if(constraints && constraints.other) {
var otherInput = dijit.byId(constraints.other);
if(otherInput) {
var otherValue = otherInput.value;
console.log("%s == %s ?", value, otherValue);
isValid = (value == otherValue);
}
}
return isValid;
}
function onsubmit()
{
var p1 = dijit.byId('password1').value;
var p2 = dijit.byId('password2').value;
return p1 == p2;
}
and the input objects:
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
intermediateChanges=false
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
constraints="{'other': 'password1'}"
validator=confirmPassword
intermediateChanges=false
invalidMessage="This password doesn't match your first password" /></p>
Even easier, use the pre-written Dojox widget, dojox.form.PasswordValidator.
http://docs.dojocampus.org/dojox/form/PasswordValidator
It does everything you want straight out of the box!
I've solved it!
This page on the Dojo forum was helpful.
I changed the HTML for the confirm password to:
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
validator="return theSame(this, dijit.byId('password1'));"
invalidMessage="This password doesn't match your first password" /></p>
The only difference is the added validator parameter.
And I created the following JavaScript function:
function(dojoTxt1, dojoTxt2) {
return dojoTxt1.getValue() == dojoTxt2.getValue();
}
I think you can also use the validator parameter to create regular expressions to test against, but the documentation isn't very clear.