Javascript function not modifying html - javascript

I have a problem with a Javascript function. It is supposed to check if two input boxes in a form have the same value, using an if statement.
HTML:
<form action="confirm_account.php" method="post" id="form" onsubmit="checkpassword()">
<p style="font-family:latine;">Password: <input type="password" name="password" id="password" style="font-family:latine;" required>
</p>
<br><br>
<p style="font-family:latine;">Re-enter Password: <input type="password" name="password-reenter" id="password-reenter" style="font-family:latine;" required> </p>
<span id="password-warning" style="color:red; font-weight:bold;"></span>
Javascript:
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
function checkpassword(){
if('password' == 'password2'){
document.getElementById("form").action = "confirm_account.php";
document.getElementById("password-warning").innerHTML = "";
}
else{
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
document.getElementById("form").onsubmit = "return false";
}
};
The warning message shows up, but the onsubmit is not modified.

Try this, it should work:
function checkpassword() {
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
if (password === password2) {
document.getElementById("form").action = "confirm_account.php";
document.getElementById("password-warning").innerHTML = "";
document.getElementById("password-success").innerHTML = "The passwords match! Well done!";
} else {
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
document.getElementById("password-success").innerHTML = "";
document.getElementById("password-reenter").focus();
return false;
}
}
<form action="#" method="post" id="form" onsubmit="return checkpassword()">
<p style="font-family:latine;">Password:
<input type="password" name="password" id="password" style="font-family:latine;" required>
</p>
<br>
<p style="font-family:latine;">Re-enter Password:
<input type="password" name="password-reenter" id="password-reenter" style="font-family:latine;" required>
</p>
<p>
<span id="password-success" style="color:green;"></span>
<span id="password-warning" style="color:red; "></span>
<input type="submit" name="btnSave" value="Try it">
</form>

var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
In your if condition, you're not checking password and password2 instead you are actually checking the strings.
It should be
if(password === password2){
And onsubmit is an event and you can't assign string to it. As you're calling checkpassword from onsubmit of form. To prevent form submission just return false.
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
function checkpassword(){
if(password === password2){
document.getElementById("password-warning").innerHTML = "";
}
else{
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
return false;
}
};

Related

My signup button disappears while filling out my password on a form

This is a two-part question.
Part 1. The passConfirm function that I currently have is there to make sure that the password and confirming password values match. Right now, when I type in my password the button disappears. The purpose of this function is to display a message while the user is creating a password and confirming it, that the password does or does not match. Does anyone know why that is happening based on the code I have?
Part 2. Is there a way to refactor my passConfirm function? I tried doing it by adding it to the validateForm function (Please see commented code for my example). It wasn't working tho.
function printError(elemId, message) {
document.getElementById(elemId).innerHTML = message;
}
function validateForm() {
event.preventDefault();
var name = document.regForm.FullName.value;
var email = document.regForm.email.value;
var phone = document.regForm.phone.value;
var password = document.regForm.Password.value;
var confirmPassword = document.regForm.ConfirmPassword.value;
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var nameError = emailError = phoneError = passwordError = true;
//Empty name input error message
if (name == "") {
printError("nameError", "Please enter your name")
}
//Empty email input error message
if (email == "") {
printError("emailError", "Please enter a valid email")
}
//Empty phone input error message
if (phone == "") {
printError("phoneError", "Please enter your phone numnber")
}
//Non valid phone number error messsage
if (phone.match(phoneno)) {
return true;
} else {
printError("phoneError", "Please enter a valid phone number")
}
//Empty Password input
if (password == "") {
printError("passwordError", "Please enter a password")
}
//Empty Cofirm Password input
if (confirmPassword == "") {
printError("confirmpassError", "Please confirm your password")
}
//I tried refactoring the passConfirm function and additing it here.
//if (password.match(confirmPassword)) {
// printPass("matchingPassword", "Passwords match")
// document.getElementById("matchingPassword").style.color = "green";
//} else {
// printPass("matchingPassword", "Passwords do no match")
// document.getElementById("matchingPassword").style.color = "red";
//}
};
var passConfirm = function() {  
if (document.getElementById("Password").value ==    document.getElementById("ConfirmPassword").value) {   
document.getElementById("matchingPassword").style.color = "green";   
document.getElementById("matchingPassword").style.fontWeight = "Heavy";   
document.getElementById("matchingPassword").innerHTML = "Passwords match!"  
} else {   
document.getElementById("matchingPassword").style.color = "red";   
document.getElementById("matchingPassword").style.fontWeight = "Heavy";   
document.getElementById("matchingPassword").innerHTML = "Passwords do NOT match!"  
} 
}
fieldset {
width: 420px;
height: 950px;
}
<h1>Hello, please register!</h1>
<div class="container">
<form name="regForm" class="form" onsubmit="return validateForm(event)">
<fieldset>
<div class="row">
<label>Full Name</label></br>
<input name="FullName" type="text" placeholder="John Doe" id="FullName" />
<span class="error" id="nameError"></span>
</div>
<div class="row">
<label>Email</label></br>
<input name="email" type="email" placeholder="johndoe#email.com" id="Email" />
<span class="error" id="emailError"></span>
</div>
<div class="row">
<label>Phone Number</label></br>
<input name="phone" type="tel" placeholder="(123) 456-7890" id="PhoneNumber" />
<span class="error" id="phoneError"></span>
</div>
<div class="row">
<label>Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onchange='passConfirm();' />
<span class="error" id="passwordError"></span>
</div>
<div class="row">
<label>Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onchange='passConfirm();' />
<span class="error" id="confirmpassError"></span>
</div>
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button>
</fieldset>
</form>
</div>
Your button disappears because you use InnerHTML method to display the message, which overrides it. Though your logic works after passwords match when you press enter, you lose your button element. It is better to use a separate div or paragraph tag to display your message and keep your button as it is since it's part of the form.
Here is the change you can try
<span id="matchingPassword">
<button type="submit" value="submit">Sign Me Up!</button></span>
<p id="message"></p>
</fieldset>
var passConfirm = function() {
if (document.getElementById("Password").value == document.getElementById("ConfirmPassword").value) {
document.getElementById("message").style.color = "green";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
} else {
document.getElementById("message").style.color = "red";
document.getElementById("message").style.fontWeight = "Heavy";
document.getElementById("message").innerHTML = "Passwords match!"
}
}

Encrypt Password

I have a login page having username and password after successful entry of username and password, it forward to the login controller.
My problem is that while forwarding to next page, in url the password enter is showing. I need to encrypt that and send over controller and have to decrypt that over controller.
this is my code.
jsp:
<form action="Login" onsubmit="return validate1()">
<h3>
<font color="red">username</font>
</h3>
<input type="text" name="username" id="username" /><br>
<h3>
<font color="red">password</font>
</h3>
<input type="password" name="password" id="password" /><br> <input type="submit" value="submit" />
</form>
javascript:
<script>
function validate1() {
return validate();
}
function validate() {
var isValid = true;
var name = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (name.length == 0) {
isValid = false;
alert("Username empty");
} else if (password.length == 0) {
isValid = false;
alert("Password empty");
}
return isValid;
}
</script>
url:
http://localhost:8080/PSMS/Login?username=jay&password=jay
here password is visible I need to encrypt the password and forward to controller where again I have to decrypt that password.
I think you need add an attribute to your form tag.
<form method="post"> ...

Submitting form even when validation regex is wrong

i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>

JavaScript form validation second if statement not working

I'm starting simple JavaScript form validation. I write two statement, first if statement working well but second one is not. But this two if statement separately working. I don't understand what I'm wrong. Here is the HTML code:
<form id="loginForm" name="loginForm" method="post" action="my-profile.html">
<div class="form-group">
<label>Email</label>
<input type="email" name="email" id="eMail" placeholder="abcde00#example.com" class="form-control" required="required" />
<span class="erRor" id="error1">Please input valid email address</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="Password" name="password" id="pasSword" class="form-control" required="required" />
<span class="erRor" id="error2">Invalid email and password</span>
<span class="erRor" id="error3">This field should not be empty</span>
</div>
<div class="form-group">
<button type="submit" onclick="return validate();">Login</button>
</div>
</form>
JavaScript code here:
function validate(){
/* email validation */
var changeColor = document.getElementById("eMail");
var error1 = document.getElementById("error1");
var email1 = document.loginForm.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,}))$/;
if(!re.test(email1.value)){
changeColor.style.border = "2px solid red";
error1.style.display = "block";
return false;
}
/* empty fild check for password field */
var pas = document.getElementById("pasSword");
var error3 = document.getElementById("error3");
var password = document.loginForm.password;
if(password.value === ""){
pas.style.border = "2px solid red";
error3.style.display = "block";
return false;
}
}
Please help me out of this.
Note: I want to learn "AS YOU TYPE JavaScript for validation". I haven't find any proper tutorial or desiccation.
You are using return false, hence second validation is not working.
Try this:
var valid = true;
if(conditoin_one){
valid = false;
// update error element
}
if(conditoin_two){
valid = false;
// update error element
}
return valid;

Validate email field in the form while adding to the list

I am adding users to the list using pure js and I am trying to validate the email field using ajax. How to validate the email field before submitting the form? If the email field is valid then i want to submit or else I have show the error in valid email.
Here is the code
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
if you using js then below code will definitely help you.
if (document.getElementById('email').value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(document.getElementById('email').value) == true) {
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
edited code: u have to just replaced it with your code, hope will work for you:
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
else {
alert("Please Enter Valid Email Id");
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
Try This
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="email" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = email.match(emailPat);
if (EmailmatchArray == null) {
email.focus(); }
else {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
}
return false;
}
DEMO HERE
Try this
It will validate the field , then add the info to list
<form id="myform" onsubmit="return addUser();">
<h2>Add a User:</h2>
<input id="username" type="text" required name="username" placeholder="name">
<input id="email" type="email" required name="email" placeholder="email">
<button type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
DEMO
For the simple validation use the following way (type="email")
<input id="email" type="email" name="email" placeholder="email">
Here is the w3schools link http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validate_email
For Depth use this :
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
//Your Code here
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</form>
Try this
function addUser() {
var email = document.getElementById('email').value;
var username =document.getElementById('username').value;
$.post('/url/to/validation/email/from/db', { "email": email, "username": username }, function(data) {
if(data && data.Success){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
document.getElementById('users').appendChild(entry);
}else{
alert('Email already exists!');
}
},'json');
return false;
}
This will validate the entered email against server and then adds to the list.

Categories