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>
Related
I am trying to validate three fields within my form. I have written the code for them and thought they would work. The only problem I'm having is that they're not done in a sequence. If i submit the form without filling in anything, it picks up the email validation.If i fill in the first name, again skips the first name and surname validation and goes straight to email. I tried to make it work in a sequence so first name first then surname and email. Any help would be appreciated.
JS
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
}
function validateForm() {
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
}
function validateForm() {
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
HTML
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
Jsut create only one validateForm() function and inside this function validate all your fields.
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
<form name="buyProductForm" onsubmit="return validateForm()" method="post">
<fieldset id="field1">
<legend>Personal Details</legend>
<label for="name">Firstname:</label>
<input type="text" name="fname" placeholder="Enter your first name" ><br>
<label for="name">Surname:</label>
<input type="text" name="sname" placeholder="Enter your surname"><br>
<label for="email">Email Adress:</label>
<input type="email" name="email" placeholder="Enter your email" ><br>
<input type="submit" value="Submit">
</form>
function validateForm() {
var fname = document.forms["buyProductForm"]["fname"].value;
if (fname == "") {
alert("Firstname must be filled out");
return false;
}
var sname = document.forms["buyProductForm"]["sname"].value;
if (sname == "") {
alert("Surname must be filled out");
return false;
}
var email = document.forms["buyProductForm"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
}
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>
I'm trying to use javascript to perform client-side verification of input to the following form. The 'firstname' field should contain only alphabetical characters. How can I write the validation function to implement this behaviour?
form.html
<html>
<head>
<script type="text/javascript" src="mainform.js"></script>
</head>
<body>
<form name="mainform" method="post" onSubmit="return validation();" >
firstname <input type="text" name="firstname"><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit">
</body>
</html>
form.js
function validation()
{
var fname=document.mainform.firstname;
var letters="/[a-zA-Z]$/";
if(fname.value.match(letters)){
return true;
}
else
{
alert('first name must be alphabets');
fname.focus();
return false;
}
}
function validation()
{
var fname = document.mainform.firstname;
if(/^[a-zA-Z]+$/.test(fname.value)) {
return true;
} else {
alert('first name must be alphabets');
fname.focus();
return false;
}
}
Do not forget to make a check on the server side too for security.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hide</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style type="text/css">
label input[type="button"]
{
background: #E17698;
}
</style>
<script>
$(document).delegate("#submit","click",function(e)
{
var name = $("#fname").val();
var hasError = false;
var searchReg = /^[a-zA-Z ]+$/;
if(name == '') {
$("#txtt").after('<span class="error" style="color:red;"> *Fill Name Box</span>');
hasError = true;
} else if(!searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:red;"> **Enter Vaild Name.</span>');
hasError = true;
}else if(searchReg.test(name)) {
$("#txtt").after('<span class="error" style="color:white;"> Vaild Name</span>');
}
if(hasError == true) {
return false
}
});
</script>
</head>
<body>
<form name="mainform" method="post">
firstname <input type="text" name="firstname" id='fname'><label id="txtt"></label><br>
lastname <input type="text" name="lastname"><br>
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
confirm password<input type="password" name="cpassword"><br>
email <input type="email" name="email"><br>
phone no <input type="text" name="phoneno"><br>
<input type="submit" name="submit" id='submit'>
</form>
</body>
</html>
I am creating a login/register part to a site. And the login and register forms are on page.
Like:
<form name="loginform" style="text-align:center;" method="post" onsubmit="return validateForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email" autocomplete="off" placeholder="Email Address" />
</div>
<br />
<div class="row">
<input type="password" name="password" id="password" autocomplete="off" placeholder="Password" />
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Log Me In</button>
</div>
</form>
<form name="registerform" style="text-align:center;" method="post" onsubmit="return validatethisForm();" action="index.php">
<div class="row">
<input type="text" name="email" id="email2" autocomplete="off" placeholder="Email Address"/>
</div>
<br />
<div class="row">
<input type="password" name="password" id="password2" autocomplete="off" placeholder="Password"/>
</div>
<br />
<div class="row">
<button id="submit" type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</div>
</form>
My Js Validation is: ( needs work )
function validateForm()
{
var x=document.forms["loginform"]["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;
}
var x=document.forms["loginform"]["password"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
function validatethisForm()
{
var x=document.forms["registerform"]["email2"].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;
}
var x=document.forms["registerform"]["password2"].value;
if (x==null || x=="")
{
alert("Please enter a Password");
return false;
}
}
The issue I have is page validation, everything works perfect. But because I have duplicate submit id's , I need to clean this up.
Can you offer suggestions on improving my code above ?
/////////////////////////////////////////
Using: code below for cross browser placeholder
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
I simplified your HTML code to the following:
<form name="loginForm" method="post" onsubmit="return validateForm();" action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Log In</button>
</form>
<form name="registerForm" method="post" onsubmit="return validatethisForm();"
action="index.php">
<label>Email Address: <input type="email" name="email" autocomplete="off" placeholder="Email Address"/></label>
<label>Password: <input type="password" name="password" placeholder="Password"/></label>
<button type="submit" class="button large arrow-type-2 dark">Create Free Account</button>
</form>
Points
Always include a label. Not all browsers support HTML5 placeholders.
All IDs here are reluctant. Forms can be accessed by
var loginForm = document.forms.loginForm; //By name
and form elements by
loginForm.email; //Also by name
No need for divs and brs to manage the line breaks. Use the labels themselves. Add display: block; as necessary.
Don't use inline style attribute. Use a CSS <style> element or an external stylesheet.
There's no AutoComplete on password fields.
Use HTML5's new form input types. type="email" will have the browser natively validate the field and notify the user if the email is not valid.
Keep it simple. No need for bloating.
Since both functions do the same thing, just make one function and bind it to both forms 'onsubmit' event.
You taggued is as jquery ,so, jquery-style, using Mike Alsup's jQuery Form Plugin.
function validate(formData, jqForm, options) {
// formData is an array of objects representing the name and value of each field
// that will be sent to the server; it takes the following form:
//
// [
// { name: username, value: valueOfUsernameInput },
// { name: password, value: valueOfPasswordInput }
// ]
//
// To validate, we can examine the contents of this array to see if the
// username and password fields have values. If either value evaluates
// to false then we return false from this method.
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
$('form').ajaxForm( { beforeSubmit: validate } );
This example and more info here.