Form Validation doesn't validate for Password - javascript

I can't see what's wrong. When I try to validate email it works fine, but it doesn't check for the password at all! It's literally the simplest a program can get.
function validateForm() {
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
if (email == "") {
alert("Email must be filled out");
document.getElementById("emailE").innerHTML = "<font color=\"red\"> Pls fill in email.</font>";
return false;
}
else if (password == "" && password.length > 8) {
alert("Password must be filled out");
document.getElementById("passwordE").innerHTML = "<font color=\"red\"> Pls fill in password and it should be greater than 8 chars.</font>";
return false;
}
}
</script>
</head>
<body>
<h1>School Form</h1>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
<table cellspacing="10">
<tr>
<th>Email:</th>
<th><input type="email" name="email"></th>
<th><span id="emailE"></span></th>
</tr>
<tr>
<th>Password:</th>
<th><input type="password" name="password"></th>
<th><span id="passwordE"></span></th>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>```

You are checking the email and not password because once the first if statement is true it will not go to the else if of the same block so use them in different blocks of if else statement or use both of them in one if statement
secondly you are checking for the length of password is more than 8 and its value is '' so this is impossible to have.
Here are some suggestions
Font tag is depreciated a long ago so don't use this

Related

The messages are not properly being displayed on my webpage in javascript. The message only displays after clicking in and out of the textbox twice.

I wrote several functions to check if the two passwords are equal. I first type two passwords. When I click out of the "verify password" box, it should either display "The passwords match" or "Please enter your password again because the two passwords don't match" depending on whether or not the passwords are equal to each other. However, when I type in two identical passwords and I click out of the "verify password" text box, the message does not display the first time. I have to click inside the "verify password" box one more time, and then click out of it for the message to display. I want the message to display right after I click out of the "verify password" textbox, not having to click in and out again. What am I doing wrong here?
I am using a password.js file and a setpassword.html file for this webpage.
My password.js file is:
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
if(password1 == '' || verifypassword == '') {
return null;
}
if(password1 == verifypassword) {
alert('The passwords match');
}
else if(password1 !== verifypassword || password1 == "" || verifypasword == "") {
alert("Please enter your password again because the two passwords don't match");
}
}
verifypasswordclick.onblur = function() {
verifypasswordclick.addEventListener("blur",verifypassword1);
};
My setpassword.html file is:
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register Here</title>
</head>
<body>
<h2>Register Here</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password" required></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td> </td>
<td>
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
<script src = "password.js"></script>
</body>
</html>
The password is verified second time because, the eventListener is added to the element only after the first onblur event. To work in first time don't add the eventListener with in the onBlur function. Refer the below js code.
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
if (password1 == verifypassword) {
alert('The passwords match');
}
else if (password1 !== verifypassword || password1 == "" || verifypasword == "") {
alert("Please enter your password again because the two passwords don't match");
}
}
verifypasswordclick.addEventListener("blur", verifypassword1);

Javascript wrong redirecting when submitting

Here is my javascript code to check whether the user has entered values for username and password fields. When I run this, it shows me the correct alerting messages but the form is seems to be submitted even it returns false. Can someone helps me?
<script type="text/javascript">
function loginValidate(){
if (document.getElementById("username").value==''){
window.alert("Please enter your username");
if (document.getElementById("password").value==''){
window.alert("Please enter your username and password");
return false;
}
}
if (document.getElementById("password").value==''){
window.alert("Please enter your password");
return false;
}
return true;
}
</script>
<form onsubmit="loginValidate()">
<input type="submit" name="submit" id="submit" value="Login" />
</form
You need to return the value returned by the function to the handler:
<form onsubmit="return loginValidate()">
Also, do not give any form control a name or id of "submit" as it assign a reference to the control to the form's submit property, thereby masking the form's submit method (i.e. form.submit references the control, so form.submit() will fail).
There is rarely any need for a submit button to have a name or id, so:
<input type="submit" value="Login">
You can also clean up the logic a bit. If you pass a reference to the form to the function, getting the controls is easier:
<script>
function loginValidate(form){
if (form.username.value == ''){
window.alert("Please enter your username");
return false;
}
if (form.password.value == ''){
window.alert("Please enter your password");
return false;
}
return true;
}
</script>
<form onsubmit="return loginValidate(this)">
<table>
<tr><td>Username: <td><input type="text" name="username">
<tr><td>Password: <td><input type="password" name="password">
<tr><td colspan="2" style="text-align: right;><input type="submit" value="Login">
</table>
</form
Note that this sends the password in clear text so not particularly secure.

How can I differentiate between a freshly loaded form and the same form loaded after redirection

I have a login form with the following fields -
Username
Password
Return Failure
Direct Login
When I click on submit all the fields are appended in the URL and it hits a JSP file.
After this,
Scenario 1: If login is a success, it is redirected to success page. This works
Scenario 2: If login fails, it is redirected to the return failure URL value passed as parameter. While redirecting it does not give any response.
Question -
1. How can I differentiate between loading a fresh form and form loaded after redirection?
2. I have to display a warning for invalid username and password before redirecting the page to returnfailure value and not during a fresh load of form.How can I do this?
Below is the code -
**HTML**
<form name="formlogin" method="get" onsubmit="return ValidateForm();" class="form-wrapper">
<table>
<tr>
<td>
<label class="service-lable" style="font-family:Verdana;">Username</label>
</td>
<td>
<input type="email" name="username" maxlength="30" size="30" class="required"/> <br/><br/>
</td>
</tr>
<tr>
<td>
<label class="service-lable" style="font-family:Verdana;">Password</label>
</td>
<td>
<input type="password" name="password"maxlength="30" size="30" class="required"/> <br/><br/>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="directlogin" id="directlogin" value="1"/>
</td>
<td>
<input type="hidden" name="returnfailure" id="returnfailure" value="http://www.google.com"/>
</td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="" class="button_add" />
</td>
</tr>
</table>
</form>
**Javascript**
<script>
function emailcheck(str) {
var at="#";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (lat ==-1 || lat == 0 || lat == lstr){
return false;
}
if (ldot==-1 || ldot==0 || ldot == lstr){
return false;
}
if (str.indexOf(at,(lat+1))!=-1){
return false;
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
return false;
}
if (str.indexOf(dot,(lat+2))==-1){
return false;
}
if (str.indexOf(" ")!=-1){
return false;
}
return true;
}
function ValidateForm(){
var emailID=document.forms["formlogin"].username;
var username=document.forms["formlogin"].username.value;
username=username.toLowerCase();
var password=document.forms["formlogin"].password.value;
if ((emailID.value==null)||(emailID.value == "")){
// alert("Please Enter your Email ID");
emailID.focus();
return false;
}
if (emailcheck(emailID.value)== true){
document.forms["formlogin"].action = "http://www.test.com/login.jsf";
return true;
} else {
alert ('Please enter the valid Email ID');
return false ;
}
}
</script>
TJ is on the right track. Usually here you want to have the server be able to pass the contents of the form as well as the error to the client when the page loads (even the first time). If you want to do this entirely client side, perhaps you could have the form submit take the place of a javascript ajax request. The javascript can then interpret the server response and then either populate the page with the error message or redirect to the success page.

JavaScript Form, with validation

I am currently using html to code a 'form entry'. I am also using a JavaScript validation, to validate the input in of the form. So far, i have the 'name', 'subject' and 'Examination number'. However my validation does not work for my Examination number. for examination number, i want the validation to make sure that the input is only 4 digits, hence i added 'maxlength="4"'. If someone could please help me with this validation to firstly validate the examination number and ensure that the input is four digits, it would be very helpful, thanks
here is my code:
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.Examination_number.value=="4") {
msg+="You must enter your Examination number \n";
document.ExamEntry.Examination_number.focus();
document.getElementById('Examination_number').style.color="red";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width="60%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
it's not .value == "4" it's .value.length == 4
You can actually use html5 for this, no javascript required!
Along with the maxlength attribute, include this attribute:
pattern="\d{4}"
the "pattern" attribute allows you to specify a regex pattern for validating the input.
\d is regex meaning "digits". {4} is regex meaning repeat exactly 4 times.
The maxlength attribute is actually redundant now, and can be removed since the regex will limit the length of the input on its own.
So overall, your element can look like:
<input type="text" pattern="\d{4}" name="Examination_number" />
Also just one note: It's also important to keep in mind that client side validation is not equivalent to server-side validation. Anyone with basic webdev knowledge will still be able to post invalid Examination_Number values to your server. Your server must be able to validate these values as well.
Use regex... var regex = /^\d{4}$/;
And of course, sorry, you can do it matching the regex... if (regex.test(examinationnumber)) then good..
You could also check the value with isNaN to be sure of getting numbers, like:
if (!isNaN(examinationnumber)) then good..
To make them alltogether:
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}

How do i create an email button that will submit to web form php?

So I am trying to make a javascript function in html that will accept email addresses and then submit them to a web form. How do I do this? this is what I have so far:
<html>
<form name="form" method="post" action="form-action.php">
<label>
Email:
</label>
<input type="email" name="email"
id="email" size="25" />
<input type="button" value="Submit" onclick="SubmitEmail()" />
</form>
<script type="text/javascript">
function SubmitEmail() {
if (!ValidateForm()) {
return false;
}
document.getElementById("form").submit();
function ValidateForm() {
if (document.getElementById('email').value.length === 0) {
alert("Email is Required");
return false;
}
document.getElementById('EmailRslt').value = document.getElementById('email').value;
return true;
}
</script>
<td>Your Email is:
</td>
<td id="EmailRslt"></td>
</html>
in your form-action.php fire insert query which will submit
data in your database table.
replace if (document.getElementById('email').value.length === 0) this line with
if (document.getElementById('email').value.length == 0)

Categories