I'm new to the web programming can you please tell me what's wrong with following code?
<!doctype html>
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate (form) {
// valriable declaration
var returnValue = true;
var username = form.txtUserName.value;
var password1 = form.txtPassword.value;
var password2 = form.txtPassword2.value;
// check for UserName length
if (username.length < 6) {
returnValue = false;
alert("Your username must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtUserName.focus();
};
// check for password length
if (password1.length < 6) {
returnValue = false;
alert("Your password must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
// check for match of password field
if (password1.value != password2.value) {
returnValue = false;
alert("Your password entries did not match.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
};
return returnValue;
}
</script>
</head>
<body>
<form method="post" name="frmRegister" action="register.html" onsubmit="return validate(this);">
<div><label for="txtUsername">UserName : </label>
<input type="text" name="txtUserName" id="txtUserName" size="12" />
</div>
<div><label for="txtPassword">Password : </label>
<input type="text" name="txtPassword" id="txtPassword" size="12" />
</div>
<div>
<label for="txtPassword2">Confirm your password : </label>
<input type="text" name="txtPassword2" id="txtPassword2" size="12" />
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
</body>
</html>
first of all stop using return from event handler.
convert your code to
<form ... onsubmit="validate(event,this)">
change your function to validate(event,form);
wherever you feel form should not be submitted..
write :
event.preventDefault()
instead of return false
Demonstration :
http://codepen.io/anon/pen/kGmeL
Related
If I click the generate button I want the following passwords to appear "abcd" "1234" "!##$" in the three empty boxes but I missed my class about this lesson and when I tried to watch youtube videos about it I get confused so can anyone help me on How to put the passwords "abcd" "1234" "!##$" in the 3 empty boxes if I press the generate button? Thank you in advance
<html>
<head>
<h1><center>Hi! there, to enter to our website please generate your Three(3) password token and use it to Enter<center></h1>
</head>
<script>
var counter=3;
function validate()
{
while(counter>=1)
{
var token1="abcd";
var token2="1234";
var token3="!##$";
var checkToken=document.getElementById("getToken").value;
if(checkToken===token1 || checkToken===token2)
{
document.write("<center>password correct. Please click the link:");
document.write('<br> Check our site');
}
else
{
counter=counter-1;
alert("Incorrect password!\n\n Attempts left: "+counter);
if(counter==0)
{
document.write("please contact our security team.");
}
break;
}
}
}
</script>
<script>
function generate()
var pass1="abcd";
var pass2="1234";
var pass3="!##$";
</script>
<body>
<center>
<p>Generate password token</p>
<input type="text" placeholder="Create password" id="password1" readonly />
<input type="text" placeholder="Create password" id="password2" readonly />
<input type="text" placeholder="Create password" id="password3" readonly />
<br>
<input type="button" value="Generate Token" onclick="generate()">
<p>Enter password token below to continue:</p>
<input type="password" placeholder="Enter password" id="getToken">
<br>
<input type="button" value="Validate Token" onclick="validate()">
</center>
</body>
So I tried doing this but it did not work
function generate()
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
getElementById(password).innerHtml = pass1;
getElementById(passwords).innerHtml = pass2;
getElementById(passwordss).innerHtml = pass3;
Oh my God I figured it out So the correct one is
<script>
function generate(){
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
document.getElementById("password").value=pass1;
document.getElementById("passwords").value=pass2;
document.getElementById("passwordss").value=pass3;
}
</script>
I changed Innerhtml to value and I was missing {}
<html>
<head>
<h1><center>Hi! there, to enter to our website please generate your Three(3) password token and use it to Enter<center></h1>
</head>
<script>
var counter=3;
function validate()
{
while(counter>=1)
{
var token1="abcd";
var token2="1234";
var token3="!##$";
var checkToken=document.getElementById("getToken").value;
if(checkToken===token1 || checkToken===token2)
{
document.write("<center>password correct. Please click the link:");
document.write('<br> Check our site');
}
else
{
counter=counter-1;
alert("Incorrect password!\n\n Attempts left: "+counter);
if(counter==0)
{
document.write("please contact our security team.");
}
break;
}
}
}
</script>
<script>
function generate(){
var pass1 = "abcd";
var pass2 = "1234";
var pass3 = "!##$";
document.getElementById("password").value=pass1;
document.getElementById("passwords").value=pass2;
document.getElementById("passwordss").value=pass3;
}
</script>
<body>
<center>
<p>Generate password token</p>
<input type="text" placeholder="Create password" id="password" readonly />
<input type="text" placeholder="Create password" id="passwords" readonly />
<input type="text" placeholder="Create password" id="passwordss" readonly />
<br>
<input type="button" value="Generate Token" onclick="generate()">
<p>Enter password token below to continue:</p>
<input type="password" placeholder="Enter password" id="getToken">
<br>
<input type="button" value="Validate Token" onclick="validate()">
</center>
</body>
I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.
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>
this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!
I want to make a loginform using pure javascript (no libraries) and I have 2 problems!
SOLVED! by Grainier Perera
When username.value.length hits 4 characters usernameInfo.innerHTML changes back to "Please type ypur username" ! The problem is passwordInfo.innerHTML changes to "At least 6 characters" as soon as username.value.length hits 4 characters. So here is my first problem. I want passwordInfo.innerHTML to change only when I start typing in password field (onkeyup).
My second problem. When I submit the form with empty fields I want both usernameInfo.innerHTML and passwordInfo.innerHTML to change, not only usernameInfo.innerHTML.
To make it easier for u to understand the code I'll paste it all here so you can just copy it and try it yourself. Thank you!
<!DOCTYPE html>
<html>
<head>
<style>
form label {display:block; margin-top:5px;margin-left:3px;font:12px Arial;color:gray;}
form input {width:200px;padding:5px;display:inline-block; margin-top:5px;}
#submit {padding:7px;background-color:#f7af38; border:#f7af38;width:215px;display:inline-block;margin-top:15px;font:11px Tahoma;color:black;}
#usernameInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#passwordInfo {display:inline-block; font:italic 12px Arial; color:gray;}
#finalInfo {font:italic 12px Arial; margin-left:5px;}
</style>
</head>
<body>
<form method="post" action="login.php" onsubmit="return validate();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validate();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validate();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
<script type="text/javascript">
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validate()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
}
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
}
}
</script>
</div>
</body>
</html>
Try This
HTML
<form method="post" action="login.php" onsubmit="return validateForm();">
<label>Username</label>
<input id="username" name="username" type="text" onkeyup="return validateUserName();" />
<span id="usernameInfo"></span>
<label>Password</label>
<input id="password" name="password" type="password" onkeyup="return validatePassWord();" />
<span id="passwordInfo"></span>
<br />
<input type="submit" id="submit" name="submit" />
<span id="finalInfo"></span>
</form>
JavaScript
document.getElementById('usernameInfo').innerHTML = "Please type your username!";
document.getElementById('passwordInfo').innerHTML = "Please type your password!";
function validateUserName()
{
var username = document.getElementById('username');
var usernameInfo = document.getElementById('usernameInfo');
if(username.value.length < 4){
usernameInfo.style.color='red';
usernameInfo.innerHTML = "At least 4 characters!";
return false;
}
else{
usernameInfo.style.color='gray';
usernameInfo.innerHTML = "Please type your username!";
return true;
}
}
function validatePassWord()
{
var password = document.getElementById('password');
var passwordInfo = document.getElementById('passwordInfo');
if(password.value.length < 6){
passwordInfo.style.color='red';
passwordInfo.innerHTML = "At least 6 characters!";
return false;
}
else{
passwordInfo.style.color='gray';
passwordInfo.innerHTML = "Please type your password!";
return true;
}
}
function validateForm()
{
var userValid = validateUserName();
var passValid = validatePassWord();
return userValid && passValid;
}
Working Sample : link