I was doing the testing for the first time. I read the this code and made one of my own from it. The thing is that its not giving any error even if the fields are left empty.
Here is my fiddle.
Please help out. Thanks.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
{function validateForm()
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Fixed code: jsfiddle
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
if (y==null || y=="") {
alert("Password name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name*: <input type="text" name="name"> <br>
Password*: <input type="password" name="password"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
<html>
Be careful of where you place your braces. Additionally, it is advantageous to use the console on your browser to identify some errors and fixed them.
Your brace should be after function validateForm() and after the if, and at the end of the function. Overall, the braces are screwed in this example.
Lay your code out so the opening and closing braces match up and make sense to you.
You missed some braces {} and one was in the wrong spot.
Hope this works:
function validateForm() {
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["password"].value;
{
if (y==null || y=="")
alert("Password name must be filled out");
return false;
}
}
You misplaced the braces { } for validation of password. Place them after if clause.
I found it on Internet after a long time searching.. But it works just perfect..
The html code
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
the javascript
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
and the function for email validation
<script type="text/javascript">
<!--
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
you can check it online here
Related
I have been looking at some examples of form validation, where an invalid input will stop the user before proceeding to the next page. The way I have seen this done many times is using the event.preventDefault() function, but it just doesn't seem to be working for me. I'm not sure if the javascript function is wrong, or maybe it is just not being read at all. When I send in an invalid input it goes through to the next page anyway.
Here is my HTML code:
Header:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="3.css"/>
<script type="text/javascript" src="3.js"></script>
<title>Login</title>
Body:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="submit" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
and here is the referenced 3.js code:
document.getElementById("loginForm").addEventListener("submit", loginFunction, false);
function loginFunction(event)
{
var valid= true;
var elements= event.currentTarget;
var email= elements[0].value;
var pass= elements[1].value;
var regexEmail= /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass= /^(\S*)?\d+(\S*)?\W+$/;
var emailError= document.getElementById(emailError);
var passError= document.getElementById(passError);
if (email == null || email == ""){
emailError.innerHTML= "Email is empty";
valid= false;
}
else if (regexEmail.test(email) == false){
emailError.innerHTML= "Incorrect Email format";
valid= false;
}
if (pass == null || pass == ""){
passError.innerHTML= "Password is empty.";
valid = false;
}
else if (regexPass.test(pass) == false) {
passError.innerHTML= "Incorrect password format";
valid = false;
}
else if (pass.length < 8){
passError.innerHTML= "Password is too short, must be 8+ characters";
valid= false;
}
if (valid == false){
event.preventDefault();
}
}
Can anyone explain where i've made my error?
This should do the trick:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="button" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
And this:
document.getElementById('loginSubmit').addEventListener('click',loginFunction,false);
function loginFunction()
{
var valid=true;
var elements=event.currentTarget;
var email=elements[0].value;
var pass=elements[1].value;
var regexEmail=/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass=/^(\S*)?\d+(\S*)?\W+$/;
var emailError=document.getElementById(emailError);
var passError=document.getElementById(passError);
if(email==null||email=='')
{
emailError.innerHTML='Email is empty';
valid=false;
}
else if(regexEmail.test(email)==false)
{
emailError.innerHTML='Incorrect Email format';
valid=false;
}
if(pass==null||pass=='')
{
passError.innerHTML='Password is empty.';
valid=false;
}
else if(regexPass.test(pass)==false)
{
passError.innerHTML='Incorrect password format';
valid=false;
}
else if(pass.length<8)
{
passError.innerHTML='Password is too short, must be 8+ characters';
valid=false;
}
if(!valid)
{
return
}
document.getElementById('LoginForm').submit();
}
I am trying to validate various fields present in a form using Javascript. But, the fields are not getting validated. The null fields are accepted and email patter is not matched.
<script type="text/javascript">
function validateform(){
var username=document.myform.username.value;
var password=document.myform.password.value;
var course=document.myform.course.value;
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (username==null || username==""){
alert("Name can't be blank");
return false;
} if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
if (course==null || course==""){
alert("Course can't be blank");
return false;
}
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
</script>
<br>
<title>Insert Operation</title>
</head>
<body>
<div id="box">
<form name="myform" method="POST" action="Insert.php" onsubmit="return validateform()">
<div id="textbox">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
Email: <input type="text" name="email"><br><br>
Course:<input type="course" name="course"><br><br>
<input class="btn" type="Submit" value="Insert" name="done">
</div>
</form>
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.
In the codes below, both functions and callings are quite similar.
Why is it that the JavaScript validation alert works in the code below:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
but doesn't work in this one:
<!DOCTYPE html>
<html>
<head>
<title> Untitled</title>
<script type='text/javascript'>
}
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</body>
</html>
Probably because you've got a leading '}' in the code in the second example.
<script type='text/javascript'>
} // <- this is going to cause a syntax error
function validate()
{
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
return( true );
}
</script>
Try fixing that and see if it works. If you're running things in a browser, check the JavaScript console for errors.
I have a simple HTML form with just one filed. The form is as follows-
<table>
<form action="insert.php" method="post" name="discover" onSubmit="return discover()">
<tr><td></td><td><input type="text" name="name"></td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>
The validation js file is-
function discover() {
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7) {
alert("Please provide Your full name");
return false;
}
}
I have included the validation js file properly. But the validation is not working.
The link forJsfiddle
try this
<script type="text/javascript">
function check()
{
var stu_name=document.forms["discover"]["stu_name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
</script>
<form action="" method="post" name="discover" id="discover" onsubmit="return check();">
<input type="text" name="stu_name" id="stu_name" value="" />
<input type="submit" id="sub" />
</form>
In your js file,
Test that:
function discover()
{
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
This work
function discover()
{
var stu_name=document.getElementsByName("name");
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
You are mixing form name and function name and also the input needs an id which was missing. Also you forgot to close the function.
Try this
<script type="text/javascript">
function _discover()
{
var stu_name=document.forms["discover"]["stu_name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7)
{
alert("Please provide Your full name");
return false;
}
}
</script>
<table>
<form action="" method="post" name="discover" onSubmit="return _discover();">
<tr><td></td><td><input type="text" name="name" id="stu_name"> </td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>
There is Nothing Wrong in your Code except the function name as same name as form
see this link here's the working code
jsbin
function disc() {
var stu_name=document.forms["discover"]["name"].value;
if (stu_name==null || stu_name=="" || stu_name.length<7) {
alert("Please provide Your full name");
return false;
}
}
<table>
<form action="insert.php" method="post" name="discover" onSubmit="return disc()">
<tr><td></td><td><input type="text" name="name"></td></tr>
<tr><td></td><td><br><br><p class="submit"><input type="submit" id="submit" name="commit" value="Register"></p><br><br><br></td></tr>
</form>
</table>