SlideShare a Scribd company logo
5
Most read
7
Most read
8
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

PDF
JavaScript - Chapter 15 - Debugging Techniques
PDF
JavaScript - Chapter 11 - Events
PDF
JavaScript - Chapter 3 - Introduction
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
PPTX
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPTX
Form using html and java script validation
PDF
JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 11 - Events
JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 10 - Strings and Arrays
Form using html and java script validation
JavaScript - Chapter 7 - Advanced Functions

What's hot (20)

PDF
JavaScript - Chapter 4 - Types and Statements
PPTX
Lab #2: Introduction to Javascript
PDF
JavaScript - Chapter 8 - Objects
PPTX
PDF
jQuery for beginners
PDF
3. Java Script
PPT
Javascript
PDF
Basics of JavaScript
PDF
JavaScript Programming
PDF
Angular Directives
PPT
PHP - Introduction to PHP AJAX
PDF
Angular - Chapter 7 - HTTP Services
PPTX
Dom(document object model)
PPTX
jQuery
PPTX
PPT
JQuery introduction
PPT
Introduction to Javascript
PPTX
Angular Directives
PPT
Introduction to JavaScript (1).ppt
JavaScript - Chapter 4 - Types and Statements
Lab #2: Introduction to Javascript
JavaScript - Chapter 8 - Objects
jQuery for beginners
3. Java Script
Javascript
Basics of JavaScript
JavaScript Programming
Angular Directives
PHP - Introduction to PHP AJAX
Angular - Chapter 7 - HTTP Services
Dom(document object model)
jQuery
JQuery introduction
Introduction to Javascript
Angular Directives
Introduction to JavaScript (1).ppt
Ad

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

PDF
Html forms
PPTX
Form Validation in JavaScript
DOCX
PPT
Html,Css and Javascript Forms using different tags
PPT
Christopher Latham Portfolio
PPTX
Web topic 22 validation on web forms
PPT
Chapter09
PPT
Html Forms.ppt
PPTX
2-Chapter Edit.pptx debret tabour university
PPTX
Lecture 3 Introduction to HTML FORM AND CSS.pptx
PPTX
Basic Registration For me know what m.pptx
RTF
Html basics 11 form validation
 
PDF
full stack practical assignment msc cs.pdf
PPTX
Html forms
PDF
CSS_Forms.pdf
PPTX
FORMS IN PHP contains various tags and code
PPTX
Html tables, forms and audio video
PPT
Web forms and html lecture Number 4
PPTX
Html Forms for lecture BSIT SSC HCI LECTURE
PDF
Html5ppt
Html forms
Form Validation in JavaScript
Html,Css and Javascript Forms using different tags
Christopher Latham Portfolio
Web topic 22 validation on web forms
Chapter09
Html Forms.ppt
2-Chapter Edit.pptx debret tabour university
Lecture 3 Introduction to HTML FORM AND CSS.pptx
Basic Registration For me know what m.pptx
Html basics 11 form validation
 
full stack practical assignment msc cs.pdf
Html forms
CSS_Forms.pdf
FORMS IN PHP contains various tags and code
Html tables, forms and audio video
Web forms and html lecture Number 4
Html Forms for lecture BSIT SSC HCI LECTURE
Html5ppt
Ad

More from WebStackAcademy (20)

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

Recently uploaded (20)

PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
PDF
Event Presentation Google Cloud Next Extended 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PDF
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf
PDF
KodekX | Application Modernization Development
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
Event Presentation Google Cloud Next Extended 2025
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Monthly Chronicles - July 2025
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Dell Pro 14 Plus: Be better prepared for what’s coming
madgavkar20181017ppt McKinsey Presentation.pdf
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
GamePlan Trading System Review: Professional Trader's Honest Take
NewMind AI Weekly Chronicles - August'25 Week I
Top Generative AI Tools for Patent Drafting in 2025.pdf
How AI Agents Improve Data Accuracy and Consistency in Due Diligence.pdf
KodekX | Application Modernization Development
Belt and Road Supply Chain Finance Blockchain Solution
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
Chapter 2 Digital Image Fundamentals.pdf
Chapter 3 Spatial Domain Image Processing.pdf

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: