Login form validation using javascript and php - javascript

I have been trying to create a login form using JavaScript. My login form needs to do the following using JavaScript validation
login field contains only letters with a minimum of 4 and a maximum of 6 letters
password is at least 5 characters long and not more than 7 characters and contains only letters and digits with at least 1 letter and at least 1 digit
if the data is incorrect, generate an alert window with an appropriate
message and set the cursor to the incorrect input field and the form needs to be submitted to a php file which needs to validate against a text file
I tried to use regular expression to check for the login fields and password in the javascript and i have used a login .php but haven't done anything in that till now.However my JavaScript/HTML file which i have pasted below doesn't seem to work. Can anyone tell me the issue with my file?
<html>
<head>
<script>
function validateFormOnSubmit(theForm) {
reason += validateUsername(theForm.username.value)
reason += validatePassword (theForm.pwd.value)
if (reason == "") return true
else { alert(reason); return false }
}
function validateUsername(fld) {
if (fld == "")
return "No username entered"
else if((fld.length > 6) || (fld.length < 4 ))
return "value must be between 4 and 6 characters"
else if (/[^a-zA-z]/.test(fld))
return "only letters allowed"
}
function validatePassword (fld){
if (fld == ""){
return "No password entered";
}
else if (fld.length<5 ||fld.length>7 ) {
return "length shoild be b/w 4 and 7";
}
else if (!/[a-z]/.test(fld) || !/[A-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
}
</script>
</head>
<body>
<table class ="signup" border ="o" cellpadding ="2"
cellspacing ="5" bgcolor ="eeeeee">
<th colspan="2" align="center">SignupForm</th>
<form method = "post" action ="login.php" onSubmit="return validateFormOnSubmit(this)">
<tr>
<td>Your user name:</td>
<td><input name = "username" size="35" maxlength="50" type="text"></td>
</tr>
<tr>
<td>Your Password:</td>
<td><input name="pwd" size="35" maxlength="25" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</form>
</table>
</body>
</html>

In your validatePassword function, you're logic is messed up. You have:
else if (!/[a-z]/.test(fld) || !/[A-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Which basically says that if there isn't a lowercase letter, an uppercase letter, and a number then it fails. Group the upper and lower case letter checks into one logical grouping like so:
else if ( ( !/[a-z]/.test(fld) && !/[A-Z]/.test(fld) ) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Now that says as long as there is a letter (uppercase or lowercase) AND a number, then we're good on validation. You can further compress that down to something like this:
if ( !/[a-zA-Z]/.test(fld) || !/[0-9]/.test(fld)){
return "passwords rewuire one of the letters or digitys";
}
Now if you want to achieve the functionality of highlighting the field that is failing validation, you'll need to restructure your code. One way of doing that would be to do something like this:
function validateFormOnSubmit(theForm) {
var alertMsg = false,
errMsg = validateUsername(theForm.username.value);
if (errMsg !== true) {
// highlight theForm.username by changing style or class
// set focus to this field
theForm.username.focus();
alertMsg = errMsg;
}
errMsg = validatePassword(theForm.pwd.value);
if (errMsg !== true) {
// highlight theForm.username by changing style or class
// set focus to this field
theForm.username.focus();
alertMsg += errMsg;
}
if (alertMsg !== false) return true
else {
alert(alertMsg);
return false;
}
}
function validateUsername(fld) {
if (fld == "") return "No username entered"
else if ((fld.length > 6) || (fld.length < 4)) return "value must be between 4 and 6 characters"
else if (/[^a-zA-z]/.test(fld)) return "only letters allowed"
return true;
}
function validatePassword(fld) {
if (fld == "") {
return "No password entered";
} else if (fld.length < 5 || fld.length > 7) {
return "length shoild be b/w 4 and 7";
} else if (!/[a-zA-z]/.test(fld) || !/[0-9]/.test(fld)) {
return "passwords rewuire one of the letters or digitys";
}
return true;
}
Not the prettiest approach ever, but I think you get the point. Highlight the field as you wish, and notice that if there are problems with the username AND the password, then the password field is the one that gets the focus.

Related

Password validation is not working in the login form

Password validation is not working in the login form. Here is my code:
function verifyPassword() {
var str = document.getElementById("t1").value;
if (str.match(/[a-z]/g) &&
str.match(/[A-Z]/g) &&
str.match(/[0-9]/g) &&
str.match(/[^a-zA-Z\d]/g) &&
str.length >= 8)
return true;
else
return false;
}
You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.
document.getElementById('t1').addEventListener('change', function() {
if (!verifyPassword()) {
alert("Invalid password");
}
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
if (!verifyPassword()) {
event.preventDefault();
alert("Invalid password");
}
}
Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.
The syntax ?=.*[x] means that you must have the condition x in your string.
Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.
function verifyPassword() {
var str = document.getElementById("t1").value;
var regEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");
if (regEx.test(str) &&
str.length >= 8)
console.log("good")
else
console.log("bad")
}
<div class="txt_field">
<input type="password" id="t1" value="" required>
<label>Password</label>
<button onclick="verifyPassword()">Verify</button>
</div>

condtion in javascript validation not working properly

I have a textbox and a submit button
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
Here is the function code:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
now what is want is that if the user leaves the filed empty it should only highlight the textbox with backgound color red and if the username is less than 8 characters it should show the message and highlight the backgound of textbox but now even if the textbox is empty it is displaying the message which i dont want...if the field is empty it should ol
I think your second conditional is wrong. Also you can write the code much cleaner like this:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}

Javascript disable space key for change password textboxes

,Hi all,
var veri = {
YeniSifreTextBox: $('#YeniSifreTextBox_I').val(),
YeniSifreTekrarTextBox: $('#YeniSifreTekrarTextBox_I').val(),
};
if (veri.YeniSifreTextBox == '' || veri.YeniSifreTekrarTextBox == '') {
alert("Password Can not be empty!");
}
else if (veri.YeniSifreTextBox != veri.YeniSifreTekrarTextBox) {
alert("Passwords dont not match !");
}
I can control password can not be empty and passwords dont not match with above codes.
I want to disable to enter space key while user write password.
User must never use space in keyboard inside of 2 textboxes.
1.textbox YeniSifreTextBox_I
2.textbox YeniSifreTekrarTextBox_I
You can use the below javaScript code to block the space key,
function RestrictSpace() {
if (event.keyCode == 32) {
return false;
}
}
HTML
<textarea onkeypress="return RestrictSpace()"></textarea>
Hope this helps you.
<input type="number"
id="cardNumber"
name="cardNumber"
required
onKeyDown="if(event.keyCode === 32)
return false;">
You can implement the same functionality, without creating a custom function.

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

JavaScript Form Validation Not Working onSubmit

I'm working through a section of a book on form validation with JavaScript. Unfortunately, the example in the book isn't working. I understand and follow the logic behind the validation (The general idea is that if any of the individual field validation functions return a value to the validate function then an alert will display and the form will not be submitted onSubmit) , but nothing is happening onSubmit. I have looked over the script and html a few times and can't find anything wrong (I even went to the book site and copied the code from there).
Here is the html form and the JavaScript validation:
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else {alert(fail); return false }
}
</script>
<script>
function validateForename(field) {
if (field == "") return "No Forename was entered.\n"
return ""
}
function validateSurname(field) {
if (field == "") return "No Surname was entered.\n"
return ""
}
function validateUsername(field) {
if (field == "") return "No Username was entered.\n"
else if (field.length < 5) return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field) {
if (field == "") return "No Password was entered.\n"
else if (field.length < 6) return "Passwords must be at least 6 characters.\n"
else if (! /[a-z]/.test(field) || ! /[A-Z]/.test(field) || ! /[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field) {
if (isNAN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110) return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field) {
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) && (field.indexOf("#") > 0)) || /[^a-zA-Z0-9.#_-]/.test(field)) return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onSubmit="return validate(this)">
<tr><td>Forename</td><td><input type="text" maxlength="32" name="forename" /></td>
</tr><tr><td>Surname</td><td><input type="text" maxlength="32" name="surname" /></td>
</tr><tr><td>Username</td><td><input type="text" maxlength="16" name="username" /></td>
</tr><tr><td>Password</td><td><input type="text" maxlength="12" name="password" /></td>
</tr><tr><td>Age</td><td><input type="text" maxlength="3" name="age" /></td>
</tr><tr><td>Email</td><td><input type="text" maxlength="64" name="email" /></td>
</tr><tr><td colspan="2" align="center">
<input type="submit" value="Signup" /></td>
</tr></form></table>
</body>
</html>
nothing is happening onSubmit
Assuming that you really do mean that nothing is happening, and that that includes "the form being submitted" then the problem is one that could be resolved by making the HTML valid.
A form cannot be wrapped around table rows and be inside the table those rows belong to. Some browsers recover from this error my moving the form to after the table (but leaving the inputs inside the table). This means that the inputs are not inside the form and sit around doing nothing.
As a quick fix, move the form so it surrounds the table.
As a proper solution, stop using tables for layout. CSS is a good tool for form layout.
You should also take advantage of the label element, and not fill your JS with globals.
Here's a hint.. how do you spell "isNAN"?
This code is easily debugged by putting alert statements after each line of code. If you use simple debugging like this, you will find that you have some invalid syntax. I leave it to you to find the bug!
Replace isNAN with isNaN and it should work.

Categories

Resources