SlideShare a Scribd company logo
4
Most read
8
Most read
19
Most read
Team Emertxe
www.webstackacademy.com
Form Handling
JavaScript
www.webstackacademy.com ‹#›www.webstackacademy.com
Introduction to Forms
(Basic form validation)
Form Processing
• Forms are one of the key interaction elements, where the user submits information into the
website
• Upon submission of data into the form (in form of various fields) validation of the form
happens at two levels as follows
Input validation in the
browser itself by scripting
languages like JavaScript
User input is sent via network and
validated at the server side using
server side languages like PHP
Form
Validation
Form Validation – What?
• Form validation is the process of making sure that data supplied by
the user using a form, meets the criteria set for collecting data from
the user. Some examples are:
• Has the user left required field empty ?
• Has the user entered valid email address ?
• Has the user entered text in numeric field ?
• Has the user entered number in correct range ?
• Has the user entered valid date ?
Primitive version of form – Text boxes
• We were using some primitive version of form in form of text boxes
• Combining input boxes with button events can be used to implement forms
<script>
function validate() {
var numValue,formMessage;
numValue = document.getElementById("num").value;
if (isNaN(numValue) || (numValue < 5 || numValue > 20)) {
formMessage = “Not valid!";
} else {
formMessage = "OK";
}
document.getElementById("ex").innerHTML = formMessage;
}
</script>
Primitive version of form – Text boxes
<body>
<p>Please input a number between 5 and 20:</p>
<input id="num">
<button type="button" onclick="validate()">Submit</button>
<p id="ex"></p>
</body>
Accessing Data from forms
Attribute Description
formName Name attribute of the form element
formElement Value of the name attribute
Elements of a form can be accessed by document.formName.formElement
<form name ="form1" onsubmit="return validate(this);">
Username: <input type="text" name="Username"><br>
Password: <input type="password" name="Password"><br>
</form>
Accessing Data from forms
<script>
function validateForm(form){
var Username = document.form1.Username.value;
var Password = document.form1.Password.value;
if (Username.length == 0) {
alert("You must enter a username.");
return false;
}
else if(Password.length < 8){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
Form validation – Text fields
Property Description
maxLength Maximum number of character that can be entered in the text field
Placeholder Place default text (ex: some recommendation to the user)
size Specify the field width
disabled Specify whether or not the field is disabled
<input type =”text” name=”tx1” maxLength=”30”>
<input type =”text” name=”tx2” size=”10”>
<input type=”text” name=”tx3” placeholder=”Default Text”>
Form validation – Semantic text fields
Property Description
<input type=”email”> Text field with no line breaks that should hold an email address
<input type=”number”> Single-Line text field for number input
<input type=”url”> Text field with no line breaks that should hold an url.
<input type=“password”> Text field is a password, hence don’t display on the screen
<input type=“submit”> Submit button. Trigger the function that is attached with the
event onsubmit
<input type=“reset”> Reset input fields and take input again
Form validation – Text area
Text Area - Syntax
<textarea name=”field name” id =”id” rows =”nrows” cols =”ncolumns”>
Default text for the field
</textarea>
Exercise
• Enhance the customer enquiry form with the following:
o Add text a text box to enter their enquiry text
o Add additional validation points as follows:
 Text field should not be left blank
 Better email ID validation
 Check there are 10 digits entered for the mobile number
Some useful tips:
• field.value.match(regexp) will match the regular expression against the given value
www.webstackacademy.com ‹#›www.webstackacademy.com
Forms – Additional Features
(More easy way to collect user inputs)
Additional form facilities & validation
Radio button provides option to choose an item from multiple:
Validation code:
<input type="radio" id=“male">Male<br>
<input type="radio" id="female">Female<br>
if ((form.male.checked == false) && (form.female.checked == false) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
Additional form facilities & validation
Checkbox validation (ex: Terms & Condition):
Validation code:
<input type =”checkbox” id=”license”>
if ( document.form1.license.checked == false )
{
alert ( "Please check the Terms & Conditions box." );
return false;
}
Additional form facilities
Select from given set of values
Validation code:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
if ( document.form1.city.selectedIndex == 0 )
{
alert ( "Please select your City." );
return false;
}
Exercise
• Write a JavaScript program to create a Pizza order form:
 Create radio button to select pizza (Simply Veg / Veg Supreme / Veg Delight)
 Create radio button to select pizza size (Personal Pan / Medium / Large)
 Create radio button to select crust (Thin / Normal / Special)
 Create a drop down list to select payment option (COD / Credit Card / PayTM / Debit Card)
 Create check box to agree terms & conditions
 Facility to enter discount code with limited size of the field (Have some code like PIZDIS090)
 Take customer details (Name, Email ID and Phone number)
 Display complete details entered by the user
 Add appropriate validation checks as necessary
www.webstackacademy.com ‹#›www.webstackacademy.com
Validation APIs
(Functions provided by JavaScript for form validation)
JavaScript – Validation APIs
Additional validation APIs provided by JavaScript
Property Description
checkValidity() Returns a Boolean indicating whether or not the current value of the element
is valid. It contains automatically populated error message in the field named
“validationMessage”
rangeOverflow Returns true if the element's value is larger than the element's max value.
rangeUnderflow Returns true if the element's value is less than the element's min value.
<input id="id1" type="number" min="100" max="300"
<button onclick="myFunction()">OK</button>
Check Validity example
<script>
function rangeFunction() {
var myInput = document.getElementById("id1“);
if (!myInput.checkValidity())
{
msg = myInput.validationMessage;
}
else
{
msg = "Input OK";
}
document.getElementById("demo").innerHTML = msg;
}
</script>
Range Overflow example
<script>
function rangeFunction() {
var msg = "";
if (document.getElementById("id1").validity.rangeOverflow)
{
msg = "Value too large";
}
else
{
msg = "Input OK";
}
document.getElementById("demo").innerHTML = msg;
}
</script>
WebStack Academy
#83, Farah Towers,
1st Floor, MG Road,
Bangalore – 560001
M: +91-809555 7332
E: training@webstackacademy.com
WSA in Social Media:

More Related Content

What's hot (20)

PPTX
Html forms
Himanshu Pathak
 
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PPTX
Javascript 101
Shlomi Komemi
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PDF
JavaScript - Chapter 11 - Events
WebStackAcademy
 
PPT
Php Lecture Notes
Santhiya Grace
 
PPT
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
PPTX
Css selectors
Parth Trivedi
 
PPT
Html forms
M Vishnuvardhan Reddy
 
PPT
Document Object Model
chomas kandar
 
PDF
Javascript basics
shreesenthil
 
PDF
Bootstrap
Jadson Santos
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
PPTX
Javascript validating form
Jesus Obenita Jr.
 
PDF
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
PDF
Regular expression in javascript
Toan Nguyen
 
PPT
Introduction to JavaScript
Andres Baravalle
 
PPT
Beginners PHP Tutorial
alexjones89
 
PPTX
Dom(document object model)
Partnered Health
 
PPTX
Bootstrap 5 ppt
Mallikarjuna G D
 
Html forms
Himanshu Pathak
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Javascript 101
Shlomi Komemi
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Php Lecture Notes
Santhiya Grace
 
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
Css selectors
Parth Trivedi
 
Document Object Model
chomas kandar
 
Javascript basics
shreesenthil
 
Bootstrap
Jadson Santos
 
Lab #2: Introduction to Javascript
Walid Ashraf
 
Javascript validating form
Jesus Obenita Jr.
 
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy
 
Regular expression in javascript
Toan Nguyen
 
Introduction to JavaScript
Andres Baravalle
 
Beginners PHP Tutorial
alexjones89
 
Dom(document object model)
Partnered Health
 
Bootstrap 5 ppt
Mallikarjuna G D
 

Similar to JavaScript - Chapter 14 - Form Handling (20)

PPTX
Form Validation in JavaScript
Ravi Bhadauria
 
PPTX
Form using html and java script validation
Maitree Patel
 
PPTX
Web topic 22 validation on web forms
CK Yang
 
PPTX
Accessible dynamic forms
Dylan Barrell
 
KEY
Building & Breaking Web Forms with Quaid-JS
cliener
 
PDF
Web Forms People Don't Hate
cliener
 
PDF
A Sensational Exposé With Bewildering Demonstrations
Peter Gasston
 
KEY
HTML5 Form Validation
Ian Oxley
 
PDF
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
sabogaraony
 
PDF
04.02.JS_SimpleValidation.pdf
flutterhub
 
PDF
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
zacektopleml
 
DOCX
Option #1- Form Validation in JavaScript 1- In your text editor- open.docx
farrahkur54
 
PDF
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
adoranshamma
 
PPTX
Javascript ch7
Brady Cheng
 
PDF
WIT UNIT-4.pdf
jashmithakakavakam
 
PPTX
HTML5 Forms OF DOOM
Stephanie Hobson
 
RTF
Html basics 11 form validation
H K
 
PPT
9781305078444 ppt ch06
Terry Yoast
 
PPT
Html Forms for creating frames and frameset
hassaan903
 
PPTX
Html Forms for lecture BSIT SSC HCI LECTURE
ChristopherYSabado
 
Form Validation in JavaScript
Ravi Bhadauria
 
Form using html and java script validation
Maitree Patel
 
Web topic 22 validation on web forms
CK Yang
 
Accessible dynamic forms
Dylan Barrell
 
Building & Breaking Web Forms with Quaid-JS
cliener
 
Web Forms People Don't Hate
cliener
 
A Sensational Exposé With Bewildering Demonstrations
Peter Gasston
 
HTML5 Form Validation
Ian Oxley
 
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
sabogaraony
 
04.02.JS_SimpleValidation.pdf
flutterhub
 
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
zacektopleml
 
Option #1- Form Validation in JavaScript 1- In your text editor- open.docx
farrahkur54
 
JavaScript The Web Warrior Series 6th Edition Vodnik Test Bank
adoranshamma
 
Javascript ch7
Brady Cheng
 
WIT UNIT-4.pdf
jashmithakakavakam
 
HTML5 Forms OF DOOM
Stephanie Hobson
 
Html basics 11 form validation
H K
 
9781305078444 ppt ch06
Terry Yoast
 
Html Forms for creating frames and frameset
hassaan903
 
Html Forms for lecture BSIT SSC HCI LECTURE
ChristopherYSabado
 
Ad

More from WebStackAcademy (20)

PDF
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
PDF
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
PDF
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
PDF
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
PDF
Webstack Academy - Internship Kick Off
WebStackAcademy
 
PDF
Building Your Online Portfolio
WebStackAcademy
 
PDF
Front-End Developer's Career Roadmap
WebStackAcademy
 
PDF
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
PDF
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
PDF
Angular - Chapter 5 - Directives
WebStackAcademy
 
PDF
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
PDF
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Ad

Recently uploaded (20)

PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 

JavaScript - Chapter 14 - Form Handling

  • 3. Form Processing • Forms are one of the key interaction elements, where the user submits information into the website • Upon submission of data into the form (in form of various fields) validation of the form happens at two levels as follows Input validation in the browser itself by scripting languages like JavaScript User input is sent via network and validated at the server side using server side languages like PHP Form Validation
  • 4. Form Validation – What? • Form validation is the process of making sure that data supplied by the user using a form, meets the criteria set for collecting data from the user. Some examples are: • Has the user left required field empty ? • Has the user entered valid email address ? • Has the user entered text in numeric field ? • Has the user entered number in correct range ? • Has the user entered valid date ?
  • 5. Primitive version of form – Text boxes • We were using some primitive version of form in form of text boxes • Combining input boxes with button events can be used to implement forms <script> function validate() { var numValue,formMessage; numValue = document.getElementById("num").value; if (isNaN(numValue) || (numValue < 5 || numValue > 20)) { formMessage = “Not valid!"; } else { formMessage = "OK"; } document.getElementById("ex").innerHTML = formMessage; } </script>
  • 6. Primitive version of form – Text boxes <body> <p>Please input a number between 5 and 20:</p> <input id="num"> <button type="button" onclick="validate()">Submit</button> <p id="ex"></p> </body>
  • 7. Accessing Data from forms Attribute Description formName Name attribute of the form element formElement Value of the name attribute Elements of a form can be accessed by document.formName.formElement <form name ="form1" onsubmit="return validate(this);"> Username: <input type="text" name="Username"><br> Password: <input type="password" name="Password"><br> </form>
  • 8. Accessing Data from forms <script> function validateForm(form){ var Username = document.form1.Username.value; var Password = document.form1.Password.value; if (Username.length == 0) { alert("You must enter a username."); return false; } else if(Password.length < 8){ alert("Password must be at least 6 characters long."); return false; } } </script>
  • 9. Form validation – Text fields Property Description maxLength Maximum number of character that can be entered in the text field Placeholder Place default text (ex: some recommendation to the user) size Specify the field width disabled Specify whether or not the field is disabled <input type =”text” name=”tx1” maxLength=”30”> <input type =”text” name=”tx2” size=”10”> <input type=”text” name=”tx3” placeholder=”Default Text”>
  • 10. Form validation – Semantic text fields Property Description <input type=”email”> Text field with no line breaks that should hold an email address <input type=”number”> Single-Line text field for number input <input type=”url”> Text field with no line breaks that should hold an url. <input type=“password”> Text field is a password, hence don’t display on the screen <input type=“submit”> Submit button. Trigger the function that is attached with the event onsubmit <input type=“reset”> Reset input fields and take input again
  • 11. Form validation – Text area Text Area - Syntax <textarea name=”field name” id =”id” rows =”nrows” cols =”ncolumns”> Default text for the field </textarea>
  • 12. Exercise • Enhance the customer enquiry form with the following: o Add text a text box to enter their enquiry text o Add additional validation points as follows:  Text field should not be left blank  Better email ID validation  Check there are 10 digits entered for the mobile number Some useful tips: • field.value.match(regexp) will match the regular expression against the given value
  • 13. www.webstackacademy.com ‹#›www.webstackacademy.com Forms – Additional Features (More easy way to collect user inputs)
  • 14. Additional form facilities & validation Radio button provides option to choose an item from multiple: Validation code: <input type="radio" id=“male">Male<br> <input type="radio" id="female">Female<br> if ((form.male.checked == false) && (form.female.checked == false) ) { alert ( "Please choose your Gender: Male or Female" ); return false; }
  • 15. Additional form facilities & validation Checkbox validation (ex: Terms & Condition): Validation code: <input type =”checkbox” id=”license”> if ( document.form1.license.checked == false ) { alert ( "Please check the Terms & Conditions box." ); return false; }
  • 16. Additional form facilities Select from given set of values Validation code: <select id="mySelect"> <option value="apple">Apple</option> <option value="orange">Orange</option> </select> if ( document.form1.city.selectedIndex == 0 ) { alert ( "Please select your City." ); return false; }
  • 17. Exercise • Write a JavaScript program to create a Pizza order form:  Create radio button to select pizza (Simply Veg / Veg Supreme / Veg Delight)  Create radio button to select pizza size (Personal Pan / Medium / Large)  Create radio button to select crust (Thin / Normal / Special)  Create a drop down list to select payment option (COD / Credit Card / PayTM / Debit Card)  Create check box to agree terms & conditions  Facility to enter discount code with limited size of the field (Have some code like PIZDIS090)  Take customer details (Name, Email ID and Phone number)  Display complete details entered by the user  Add appropriate validation checks as necessary
  • 19. JavaScript – Validation APIs Additional validation APIs provided by JavaScript Property Description checkValidity() Returns a Boolean indicating whether or not the current value of the element is valid. It contains automatically populated error message in the field named “validationMessage” rangeOverflow Returns true if the element's value is larger than the element's max value. rangeUnderflow Returns true if the element's value is less than the element's min value. <input id="id1" type="number" min="100" max="300" <button onclick="myFunction()">OK</button>
  • 20. Check Validity example <script> function rangeFunction() { var myInput = document.getElementById("id1“); if (!myInput.checkValidity()) { msg = myInput.validationMessage; } else { msg = "Input OK"; } document.getElementById("demo").innerHTML = msg; } </script>
  • 21. Range Overflow example <script> function rangeFunction() { var msg = ""; if (document.getElementById("id1").validity.rangeOverflow) { msg = "Value too large"; } else { msg = "Input OK"; } document.getElementById("demo").innerHTML = msg; } </script>
  • 22. WebStack Academy #83, Farah Towers, 1st Floor, MG Road, Bangalore – 560001 M: +91-809555 7332 E: [email protected] WSA in Social Media: