JavaScript Form Validation - javascript

I'm trying to create a form submission and before the form is submitted, I want to verify the credentials.
I have both this so far
HTML formatted for XHTML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title> Registration Form</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="description" content="This is a form submission with validation"/>
<script type="text/javascript" src="validScript.js"></script>
</head>
<body>
<h1>Registration Form</h1>
<form id="registration" action="" onsubmit="return validation();" method="post" enctype="text/plain">
<p>Name: <input type="text" name="name" id="name"/></p>
<p class="error">Email Address: <input type="text" name="emailAddress" id="emailAddress"/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
</body>
</html>
JavaScript:
function validation()
{
var vname = document.registration.name;
if(nameValid(vname))
{
return true;
}
return false;
}
function nameValid(vname)
{
var name_len = vname.value.length;
if (name_len == 0)
{
alert("Name is required");
vname.focus();
return false;
}
return true;
}
I'm having issues where it won't display alert the user that he/she prompted an empty name. I'm trying to valid the name and after this I'll add more functions for email address and other fields to be added. Note that this will later be used to email the form to a domain. Can someone help me figure out this problem?
Thanks

your validation function is incorrect, should be:
function validation()
{
var vname = document.getElementById("name");
if(nameValid(vname))
{
return true;
}
return false;
}
For access form elements values use document.getElementById("ElementID").value or use a javascript library like Jquery

In form add name="registration" and then check.
it will alert as you want.
and the reason is document.registration.name , where registeration is form name , not id.

If you're using jQuery I can recommend this plugin:
http://validval.frebsite.nl/
I tried quite some validation plugins before I came to this one: It has extensive validation options and it's not too fancy on the dialogs; This means easy to customize the look and feel.

Related

I am trying to ask how to get validation form through js

I am running this code. Here, I am trying to get error statement after pressing submit button but I am unable to get any error notification on html web page after typing name in 2 letters(name.length<5 will give error notification). but, I am getting nothing. Can someone look upon this code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content ="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> practice</title>
</head>
<body>
<h1><b>Welcome to the your page.</b></h1>
<form action="#" name="myForm"
method="post" onsubmit="return validateForm()">
What is your name?:
<input id="name" type="text" name="fname" placeholder="Required" required>
<span class ="formerror"></span>
<input type="submit" value="Submit">
</form>
</body>
<script>
function seterror(id,error)
{
element= document.getElementById(id);
element.getElementsByClassName
("formerror")[0].innerHTML=error;
}
function validateForm(){
var returnval = true;
var name = document.forms['myform']["fname"].value;
if(name.length<5)
{seterror("fname","length of name is too short");
returnval = false;}
//console.log('name sf');
//return false;
return returnval;
}
</script>
</html>
One way you can do this is to use the minLength (1) attribute on the input:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content ="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> practice</title>
</head>
<body>
<h1><b>Welcome to the your page.</b></h1>
<form action="#" name="myForm"
method="post" onsubmit="return validateForm()">
What is your name?:
<input id="name" type="text" name="fname" placeholder="Required" required minLength="5">
<span class ="formerror"></span>
<input type="submit" value="Submit">
</form>
</body>
First of all, you have a problem in your seterror function, but the error can't reach the console because your form will always be submitted. No matter what. So, to see what's happening, you should prevent default behaviour:
onsubmit="event.preventDefault();return validateForm()"
Then you will get an error: Cannot read properties of undefined (reading 'fname').
// 'myform' should be 'myForm'
document.forms['myform']
Your mistake #2: Uncaught TypeError: Cannot read properties of null (reading 'getElementsByClassName').
// 'element' should be 'document'
element.getElementsByClassName("formerror")[0].innerHTML = error;
Full working code:
function seterror(id, error) {
document.getElementsByClassName("formerror")[0].innerHTML = error;
}
function validateForm() {
var returnval = true;
var name = document.forms['myForm']["fname"].value;
if (name.length < 5) {
seterror("fname", "length of name is too short");
returnval = false;
}
return returnval;
}
Next steps
Don't use inline event handlers, they are harder to use. Instead you should handle events in modern way with .addEventListener().

External JavaScript file is unresponsive for form validation

I am creating an html file that links to an external JavaScript file to validate a form in my html file. Every time I hit "Submit" on my form, the page is simply re-loaded and no JavaScript is performed. I have already tried Chrome and Firefox, plus I have disabled pop-up blocking as well as ensuring JavaScript is enabled.
As far as I can tell so far, my JavaScript file is not being reached, since the first line of the single function in my JavaScript file has a call to alert(), and no pop-up or dialog windows are appearing.
My HTML, CSS, and JavaScript files are all uploaded to the same directory, and the html file is successfully linking with the CSS file because my style changes are clearly apparent.
Why won't my JavaScript file be reached?
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta name="viewport" content="width=device-width" charset="utf-8" />
<title>TitleLine</title>
<link rel="stylesheet" href="Style.css"/>
<script type="text/JavaScript" src="checkTheForm.js" >
</script>
</head>
<body>
<form name="form1" id="form1" method="post" action="" onsubmit="return validate()">
<fieldset>
<legend>Survey</legend>
<label>Name: </label>
<input type="text" name="name" id="name"/>
<input type="submit" />
<input type="reset" />
</fieldset>
</form>
</body>
</html>
JavaScript:
function validate()
{
var myDay = new Date();
var locMyDay = myDay.toLocaleDateString();
alert("testing");
console.log("hi");
if(document.forms["form1"]["name"].value == "")
{
alert("Name field is blank - please enter a name.");
document.getElementById("name").focus();
document.getElementById("name").style.backgroundColor = "#FF0000";
return false;
}
else
{
document.getElementById("name").style.backgroundColor = "#FFFFFF";
}
else
{
alert("Form successfully submitted at: " + locMyDay);
return true;
}
}

Trouble with form validation

I am trying to validate a simple form with JavaScript but cannot get the script to validate. When the Submit button is pressed there is no validation being run. If one of the boxes is left blank, the error message does not pop up to notify the user. However I am not seeing anything out of place. I am wondering if it isthe submit button is not working? Can anyone lend a hand?
<DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>LASTNAME: Warner Form Validation</title>
<script type="text/javascript">
function btnSubmit_onclick() {
var myForm = document.formContact;
if(myForm.txtAge.value == "" || myForm.txtName.value == "") {
alert.("Please complete all of the fields.");
if(myForm.txtName.vale == ""){
myForm.txtName.focus();
} else {
myForm.txtAge.focus();
} else{
alert("Thank you for completing the form"+myForm.txtName.value);
}
}
function txtAge_onblur() {
var txtAge = document.formContact.txtAge;
if(isNaN(txtAge.value) == true) {
alert("Please Enter a Valid Age");
txtAge.select();
}
function txtName_onchange(); {
window.status = "Hi" + document.form1.txtName.value;
docment.getElementById('greeting').innerHTML = "Hi" + document.frm1.txtName.value;
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validate();" name="formContact">
<p>Name:<br />
<input type="text" name="theName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="theAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p><input type="button" value="Submit" name="btnSubmit" onclick="btnSubmit_onclick></p>
</form>
<span id="results"></span>
</body>
</html>
Your code had SO many typo's. This works.
<DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>LASTNAME: Warner Form Validation</title>
<script type="text/javascript">
function btnSubmit_onclick() {
var myForm = document.formContact;
if(myForm.txtAge.value == "" || myForm.txtName.value == "") {
alert("Please complete all of the fields.");
if(myForm.txtName.vale == ""){
myForm.txtName.focus();
} else {
myForm.txtAge.focus();
}
} else{
alert("Thank you for completing the form"+myForm.txtName.value);
}
}
function txtAge_onblur() {
var txtAge = document.formContact.txtAge;
if(isNaN(txtAge.value) == true) {
alert("Please Enter a Valid Age");
txtAge.select();
}
function txtName_onchange() {
window.status = "Hi" + document.form1.txtName.value;
docment.getElementById('greeting').innerHTML = "Hi" + document.frm1.txtName.value;
}
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validate();" name="formContact">
<p>Name:<br />
<input type="text" name="txtName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="txtAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p><input type="button" value="Submit" name="btnSubmit" onclick="btnSubmit_onclick()"></p>
</form>
<span id="results"></span>
</body>
</html>
However be noted that you haven't used txtAge_onBlur or txtName_onChange functions anywhere. Also I suggest to add a numerical check to age field.
onclick="btnSubmit_onclick></p>
to
onclick="btnSubmit_onclick();"></p>
and
function btnSubmit_onclck() {
to
function btnSubmit_onclick() {
You have onsubmit="return validate();" yet I don't see validate() anywhere in your script.
Then in your script you have btnSubmit_onclck(), yet in your HTML you have onclick="btnSubmit_onclick.
So it's missing an i and in the HTML you are missing the closing ".
You also need to check the missing closing } on txtAge_onblur and btnSubmit_onclick

Can someone tell me what am i doing wrong

I am trying to get this to be if your name is Bob then you are register if not Sorry you are not allowed access but i can not figure out what I am doing wrong can someone help me thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
</head>
<script type="text/javascript">
function verify() {
var name="Please enter your name: ";
if (firstName=="Bob") {
alert("Now registered");
}
else {
window.alert("Sorry you aren't allowed acess.")
return false;
}
</script>
<form name="myForm" action="#" method="post" enctype="text/plain">
<input type="text" name="BOB">First Name<br>
<input type="button" value="Submit" onclick="verify();">
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
</head>
<script type="text/javascript">
function verify() {
var name="Please enter your name: ";
var firstName = document.getElementById('firstName').value;
if (firstName=="Bob") {
alert("Now registered");
return true;
}
else {
window.alert("Sorry you aren't allowed acess.")
return false;
} }
</script>
<form name="myForm" action="#" method="post" onsubmit="return verify();" enctype="text/plain">
<input id="firstName" type="text" name="BOB"/>First Name<br>
<input type="button" value="Submit"/>
</form>
</body>
</html>
you have to use onsubmit on form tag and it must return true or false
Note that you are missing the closing braces for the function, this code works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
</head>
<script type="text/javascript">
function verify()
{
var name="Please enter your name: ";
if (myForm.firstName.value=="Bob")
{
alert("Now registered");
}
else
{
alert("Sorry you aren't allowed acess.")
return false;
}
}
</script>
<form name="myForm" action="#" method="post" enctype="text/plain">
<input type="text" name=firstName>First Name<br>
<input type="button" value="Submit" onclick="verify();">
</form>
</body>
</html>
This should work.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
</head>
<body>
<script type="text/javascript">
function verify() {
var firstName = document.getElementById('firstName').value;
if (firstName == "Bob") {
alert("Now registered");
return true;
} else {
window.alert("Sorry you aren't allowed access.");
return false;
}
}
</script>
<form name="myForm" action="#" method="post" onsubmit="return verify();" enctype="text/plain">
<input id="firstName" type="text" name="BOB"/>First Name<br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Update your javascript like so:
<script type="text/javascript">
function verify() {
var name="Please enter your name: ";
if (document.myForm.firstName.value=="Bob") {
alert("Now registered");
return true;
}
else {
window.alert("Sorry you aren't allowed acess.")
return false;
}
}
</script>
Then update your HTML form to this:
<form name="myForm" action="#" method="post" enctype="text/plain">
<input type="text" name="firstName" value="">First Name<br>
<input type="button" value="Submit" onclick="verify();">
</form>
your onsubmit should be on the form handler (the open tag of the "form"), not on the button.
Several issues:
You don't have a javascript variable firstName anywhere. The script probably stops there.
Your form markup for the first name field is strange (why are you naming the text box "BOB"? You should give it an ID.
You need to access the form element in javascript properly.
When submitting a form, it is better to use a submit input type and hookup the form onsubmit (in this regard the answer by #Pravat is correct, though not on the other points).
This line does nothing - var name="Please enter your name: ";
Firstly the Javascript does not know what firstname is
To fix this you need to do two things:
Use the HTML <input name="BOB" id="firstName" value="" />. Note the id attribute, we'll use this to let the JS find the element we want to examine.
Then in Javascript we can find what the user has entered in the input using document.getElementById('firstName').value.
This should let you do your comparison.
To fix minor parts of your code, I believe you forgot to open your <body> tag
your also missing a } for your function
self-close your input and br tags
Try to use:
var firstName = document.getElementById('firstName').value;
and put missing } for verify function
see this..., you also have a } missing... just before the < /script> ... the missing } is the one that closes the verify function.

Use javascript to alter submit link

ok so i have a script that when you click a link it dynamicly adds a form field is it possible to make it so when it is submitted it goes to "example.com?7" (7 because of 7 files)
what i mean is if i click it 5 times and there are 5 file fields and i choose 5 files can i make the action link mysite.php?5
here is the script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="application/javascript">
function add(){
var field = document.createElement('input');
field.setAttribute("type", "file");
field.setAttribute("name", "yo");
document.getElementById('myform').appendChild(field);
}
</script>
</head>
<body>
<form id="myform" name="form1" enctype="multipart/form-data" method="post" action="">
<p>File:
<input type="file" name="hello" id="hello" />
</p>
<p>
<input name="submit" type="submit" value="Submit" />
</p>
</form>
Click Here
</body>
</html>
Thanks a lot!
I suggest giving the new added fields class = "classX" and when you submit the form count the no of elements with the specified class with getElementsByClassName
I find it simpler than incrementing a value each time a field is added
I would keep it simple and keep track of how many file fields you have added. Just update the url every time you add a new file field.
var numFileElements = 1;
function add(){
var field = document.createElement('input');
field.setAttribute("type", "file");
field.setAttribute("name", "yo");
var myForm = document.getElementById('myform');
myForm.appendChild(field);
++numFileElements;
myForm.setAttribute('action', '?'+ numFileElements);
}
Just keep an extra hidden field in the form (call it "count"), and have the script increment its value whenever it adds another file input.
Something like?
function doSubmit() {
var myForm = document.getElementById('myForm'); //Get myForm
var childNodes = myForm.childNodes; //Count child nodes
var fields = 0;
for ( var node in childNodes ) {
if ( childNodes[node].tagName == 'P' ) fields++;
}
myForm.setAttribute('action', 'mysite.php?'+fields);
}
It counts all P elements directly below myForm. Not perfect, but it ought to work! Just add an onsubmit='doSubmit();

Categories

Resources