I'm trying to make it so that i can validate the input when the user submits the form, but for some reason the javascript in my jsp isn't being implemented. any one have any idea?
code is posted below
Javascript:
function validate()
{
if(document.updateForm.fName.value == "")
{
alert(" Please provide your first name." );
document.updateForm.fName.focus();
return false;
}
{
if(document.updateForm.lName.value == "")
{
alert(" Please provide your last name." );
document.updateForm.lName.focus();
return false;
}
HTML:
<h1>People Library - Update a Person</h1>
<form name="updateForm" action="updatePerson" onSubmit="return validate()" method=get>
<Label>
Person ID:
</Label>
<input type=text name=personID value="<%= person.getPersonID() %>"/>
<br />
<Label>
First Name
</Label>
<input type=text name=fName value="" />
<Label>
<br />
Last Name
</Label>
<input type=text name =lName value="" />
<Label>
<br />
age
</Label>
<input type=text name=age value="<%= person.getAge() %>" />
<br />
<input type=submit name=submit value="Update the Person" />
</form>
There are several obvious syntax errors you would not get if you learned to properly indent code. Every time you open a curly bracket {, tab everything inside it over to make it clear where blocks begin and end.
Having done so, I find your code looks like this:
<script language="javascript" type="text/javascript">
function validate()
{
if(document.updateForm.fName.value == "")
{
alert(" Please provide your first name." );
document.updateForm.fName.focus();
return false;
}
{
if(document.updateForm.lName.value == "")
{
alert(" Please provide your last name." );
document.updateForm.lName.focus();
return false;
}
</script>
You've obviously got some missing closings }, and some stray openings {. The stray opening may be due to forgetting to type else.
Related
Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>
Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'
You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>
I'm having to dip my toe back in the EE and javascript world after many years. What am I doing wrong here... a simple form being submitted, with a JS block to validate during the onsubmit event of the submit button. The alert("Here") message box does not appear when I submit the form, and the form gets submitted successfully, i.e. HelloForm gets displayed, with blank values, so I'm led to believe that validate() is not being called. I've tried this in both the Eclipse internal web browser as well as Chrome and see the same thing both times. I'm assuming that I don't need to explicitly activate javascript in either browser, as it would be on by default.
<html>
<head>
<script>
function validate()
{
alert("Here");
var x = document.forms["inputForm"].["first_name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inputForm" action="HelloForm" method="GET" onsubmit="return validate()">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit The Form" />
</form>
</body>
</html>
In this line will throw a syntax error:
document.forms["inputForm"].["first_name"].value
^^^
The statement is wrong, should be without dot between braces:
document.forms["inputForm"]["first_name"].value
//or
document.forms.inputForm.first_name.value
Working with Objects
You can use Html5 Validations.
<form name="inputForm" action="HelloForm" method="GET" >
First Name: <input type="text" name="first_name" required />
<br />
Last Name: <input type="text" name="last_name" required />
<input type="submit" value="Submit The Form" />
</form>
Working Demo
I HAVE SEEN
similar questions & applies suggested solutions too but do not working :(
As Title Explained
i applied Java script validation but on submit button click form is submitted while fields are empty
here is the script
<script type="text/javascript">
function validate()
{
if( document.form1.name.value == "" )
{
alert( "Please provide your name!" );
document.form1.name.focus() ;
return false;
}
if( document.form1.pass.value == "" )
{
alert( "Please provide your Password!" );
document.form1.pass.focus() ;
return false;
}
return( true );
}
</script>
Form is like
<form id="form1" name="form1" method="post" action="registered.php" onsubmit="return(validate());">
<p align="center">Username :
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p align="center">Password :
<label for="pass"></label>
<input type="password" name="pass" id="pass" />
</p>
<p align="center">
<input type="submit" value="Register" />
</p>
</form>
If you are trying to get the elements value using form then use something like this
document.forms['form1'].elements['name'].value
So change your condition like this
if(document.forms['form1'].elements['name'].value == "" )
{
alert( "Please provide your name!" );
}
I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here
My Javascript code:
if (valid == false){
alert(errmsg);
return false;
}else {
var success = "Name: "+fname+" "+lname+"\n"+
"Email: "+email+"\n"+"Address: "+adr1+", "+adr2+","+
adr3+" "+zip;
alert(success);
}
all that pops up is a blank alert window.
any help or insight would be greatly appreciated.
I'm kinda new to this, let me know if you need clarifications
heres my html portion of the code
<form id="contactInfo" action="">
<p class="name">
<span class="nameHead">Name</span>
<br />
First:
<input type="text" name="fname" id="fname" />
Last:
<input type="text" name="lname" id="lname" />
</p>
<p>
Email:
<input type="text" name="email" id="email" size="55" />
<p class="address">
<span class="addressHead">Address</span>
<br />
Street:<input type="text" name="street" id="adr1" />
<br />
City: <input type="text" name="city" id="adr2"/>
<br />
State:<input type="text" name="state" id="adr3" size="2" maxlength="2"/>
<br />
ZIP Code: <input type="text" name="zipCode" id="zip" size="10" maxlength="10"/>
</p>
<p>
<input type="submit" value="Submit" onclick="return validate();" />
<input type="reset" value="Reset" />
</p>
</form>
if the user enters name, city, zip, and email wrong (searched for patterns) so my if statements look like this
if (adr1 == ''){
errmsg = errmsg + "Street address is blank\n";
valid = false;
focusA1.focus();
focusA1.select();
}else if(adr1S == -1){
errmsg = errmsg + "Street address should be in the form of digits followed by letters\n";
valid = false;
focusA1.focus();
focusA1.select();
}
if valid ends up being false at the end of the function the errmsg shows up with what is wrong and focuses on that portion of the form. One thing problem i did end up running into is that whenever the page loaded the form would automatically submit. would it have anything to do with this?
<body onload= "rotate()">
<img src="images/a.jpg" name="banner" class="banner" />
code for a rotating banner?
The way I have it set up is to show another alert for when all form fields are entered correctly and when i do enter them correctly no alert shows up
in your validation function try some thing like this
function validation()
{
var valid == true;
if(cond1)
{
alert(cond1fails);
valid=false;
}
if(cond2)
{
alert(cond2fails);
valid=false;
}
.... and so on on to all the conditions .....
// then in the last line
return valid;
}
try this it should simply work