Why isn't my span being displayed? Simple password matching - javascript

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).

Related

In my HTML document, when I tried to log out the input value, it is undefined. Why?

I've been trying to make a simple form validation js project, and my first logic statement itself had an error. When I tried to log out the value of my input it says that it is undefined:
<!--skipped css-->
<html>
<head>
<title>
Form validation
</title>
</head>
<body>
<div class="transparent">
<div class="form">
<h1 class="login"> Login </h1>
<form>
<label for="name" class="LName">Name</label>
<input class="name" id="name" name="name" placeholder="Enter your username"><br>
<label for="email" class="LEmail">E-mail</label>
<input class="email" id="email" name="email" placeholder="Enter your E-mail"> <br>
<label for="password" class="LPassword">Password</label>
<input type="password" class="password" id="password" name="password" placeholder="Enter your password"><br>
</form> <br>
<button class="btn"> Login </button>
<br> <br>
<span> OR </span><br> <hr>
<button class="gbtn"> <i class="fab fa-google"></i> Sign in with Google </button>
</div>
</div>
<script>
var name = document.getElementById('name');
var email = document.querySelector('.email');
var password = document.querySelector('.password');
var btn = document.getElementsByClassName('btn')[0];
btn.onclick = empty;
function empty() {
name = document.getElementById('name');
console.log(name.value);
if(name.value == "") {
name.classList.add('errInp');
}
}
</script>
</body>
</html>
I believe I've assigned all the vars, and I've tried changing it to innerText too, only to get another undefined. Can someone help me out?
I believe your choice of 'name' as the variable name is the problem! By assigning a variable using var name in global scope, you are clashing with window.name. Normally you set the window's name using window.name='some name' (a string). In your case where you try to assign an HTML element to it, JS calls .toString() under the hood, so the window name is actually "[object HTMLInputElement]", which has no value property.
You can solve it by changing the variable name to something else, or getting rid of the first var name = altogether and inside empty using const name = document.getElementById('name'); instead of name =....
In addition to see sharper's explanation, since the introduction of ES6, there are only few cases where declaring variables with var is a good choice. A rule of thumb is to declare a variable as const (a constant reference to a value, but not immutable) at first and change it to let later on if you need to reassign its value. Refer to this answer for a more detailed explanation.
const validateForm = () => {
const name = document.querySelector('#name').value
const password = document.querySelector('#pwd').value
if (!name || !password){
alert('invalid input')
}
else{
alert(`form is submitted for name ${name} with the password ${password}`)
}
}
Name: <input type="text" id="name">
Password: <input type="password" id="pwd">
<button onClick="validateForm()">Login</button>

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.

Validation form question bootstrap and javascript

thanks in advance for answering the question.
The goal in my form (as with many similar forms) is to check that
text field is not empty
password meets the criteria (to be honest, right now I would be happy with just anything in it)
email has text before "#", the "#" and text after "#".
depending on whether all checks are okay, to display an alert with the message.
bootstrap:
<form>
<div class="form-group">
<label for="exampleTextarea">Course/Lecturer feedback</label>
<textarea class="form-control" id="textArea" rows="3" placeholder="Please enter your feedback in this field. Your opinion matters and helps us to provide you with better serivce."></textarea>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Please enter your email address</label>
<input type="email" class="form-control" id="emailAddress" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Please enter your password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" onclick="submitData()">Submit</button>
</form>
javascript
//comment validation function
function textFieldValidate(textField){
var txtln = "";
if (txtln !=="")
return pattern.test(textField);
}
//email validation function
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
//password validation function
// at least one number, one lowercase and one uppercase letter
// at least six characters
function passwordValidate(password){
var pw = new RegExp (/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/);
return pw.test(password);
}
function submitData(){
//retrieve the values
if(textFieldValidate(textField) && isValidEmailAddress(emailAddress) && passwordValidate(password)){
//send post request
alert("Thank you for your feedback! We have sent this to KGB and you should expect a call any moment now...");
}else{
//display error message
alert("Unfortunately information that you have entered was incorrect, please check the info and and resubmit");
return;
}
}
what I get at the moment is that my page refreshes and nothing happens.
Alright, it looks like the issue was with the id in html which was called textArea and in function I called it textField.
Now... the other problem is that it doesn't really validate anything. Just the pop up appears...

JavaScript code is not working, wrote this code to validate my form but it does not work

A form that insert data into mysql but before inserting data I wanted to write a JavaScript that will validate the form before submit but can let it work. In the HTML I have added required and pattern attribute for the input to validate the form data and to check whether user fill the required fields but i also want to add a script that will also validate the form and show the a message in the tag with id errorMessage but it doesn't seem to work.
var inputFields = document.theForm.getElementsByTagName("input");
for (key in inputFields) {
var myField = inputFields[key];
var myError = document.getElementById('errorMessage');
myField.onchange = function() {
var myPattern = this.pattern;
var myPlaceholder = this.placeholder;
var isValid = this.value.search(myPattern) >= 0;
if (!(isValid)) {
myError.innerHTML = "Input does not match expected pattern. " + myPlaceholder;
} else { //pattern not valid
myError.innerHTML = "";
} //pattern is valid
} // myField has changed
} // inputFields
<form id="createForm" name="theForm" method="post" action="createUser.php">
<legend><span class="icon"><img src="/registerUser/img/createIcon.png"></span> Create New User</legend>
<p><span id="requiredfields">* required field.</span>
</p>
<span id="formMessage" class="message"> </span>
<span id="errorMessage"> </span>
<input id="fname" type="text" name="fname" placeholder="Name *" pattern="[A-Za-z ]+" required>
<br>
<br>
<input id="email" type="email" name="email" placeholder="Email *" required>
<br>
<br>
<input id="username" type="text" name="username" placeholder="Username *" required>
<br>
<br>
<input id="password" type="password" name="password" placeholder="Password *" required>
<br>
<br>
<label for="roles">Roles:</label>
<select id="role" name="roles">
<option>Select Role</option>
<option value="empty"></option>
<option value="Reporter">Reporter</option>
<option value="Lover">Lover</option>
<option value="Other">Other</option>
</select>
<br>
<br>
<input id="create" type="submit" name="createUser" value="Create User">
</form>
When you specify an input element validation pattern as an html5 attribute like this:
pattern="[A-Za-z ]+"
...the browser checks that the whole input value matches the pattern. In other words, your pattern is treated like ^[A-Za-z ]+$ even though the ^ and $ are not explicitly in the pattern.
But in your JavaScript code when you use the pattern like this:
var myPattern = this.pattern; // get pattern from element
var isValid = this.value.search(myPattern) >= 0;
...the .search() method doesn't try to match the whole string, it returns the index of the first pattern match within the string. Which means that, e.g., in the case of your Name field your JS will consider it valid as long as at least one character matches the pattern, even if other characters don't.
The simplest way to work around this is to update your pattern:
pattern="^[A-Za-z ]+$"
Or you could update your JS something to be something like the following:
var isValid = !myPattern || this.value.search("^" + myPattern + "$") >= 0;
That is, put ^ and $ around the pattern to force JS to match the whole string against the pattern, but only do the test if a non-blank pattern was specified for the field (some of your fields don't have a pattern).

Password checking in dojo

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.

Categories