Tuesday, August 16, 2016

JavaScript : HTML Form - Phone Number validation

Validating phone number is an important point while validating an HTML form. In this page we have discussed how to validate a phone number (in different format) using JavaScript :

At first we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. Here is the function.
  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\d{10}$/;  
  4.   if((inputtxt.value.match(phoneno))  
  5.         {  
  6.       return true;  
  7.         }  
  8.       else  
  9.         {  
  10.         alert("message");  
  11.         return false;  
  12.         }  
  13. }  
Flowchart :
Flowchart : JavaScript phone validation-1
To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
use the following code.
  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
  4.   if((inputtxt.value.match(phoneno))  
  5.         {  
  6.       return true;  
  7.         }  
  8.       else  
  9.         {  
  10.         alert("message");  
  11.         return false;  
  12.         }  
  13. }  
Flowchart :
Flowchart : JavaScript - phone validation-2
If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code.
  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;  
  4.   if((inputtxt.value.match(phoneno))  
  5.         {  
  6.       return true;  
  7.         }  
  8.       else  
  9.         {  
  10.         alert("message");  
  11.         return false;  
  12.         }  
  13. }  
Flowchart :
Flowchart : JavaScript - phone validation-3
Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

CSS Code

  1. li {list-style-typenone;  
  2. font-size16pt;  
  3. }  
  4. .mail {  
  5. marginauto;  
  6. padding-top10px;  
  7. padding-bottom10px;  
  8. width400px;  
  9. background : #D8F1F8;  
  10. border1px soild silver;  
  11. }  
  12. .mail h2 {  
  13. margin-left38px;  
  14. }  
  15. input {  
  16. font-size20pt;  
  17. }  
  18. input:focus, textarea:focus{  
  19. background-color: lightyellow;  
  20. }  
  21. input submit {  
  22. font-size12pt;  
  23. }  
  24. .rq {  
  25. color#FF0000;  
  26. font-size10pt;  
  27. }  
  28.               

Validate a 10 digit phone number

At first we validate a phone number of 10 digit. For example 1234567890, 0999990011, 8888855555 etc.

HTML Code

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4. <meta charset="utf-8">  
  5. <title>JavaScript form validation - checking non-empty</title>  
  6. <link rel='stylesheet' href='form-style.css' type='text/css' />        
  7. </head><br><body onload='document.form1.text1.focus()'>  
  8. <div class="mail">  
  9. <h2>Input an Phone No.[xxxxxxxxxx] and Submit</h2>  
  10. <form name="form1" action="#">  
  11. <ul>  
  12. <li><input type='text' name='text1'/></li>  
  13. <li>&nbsp;</li>  
  14. <li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>  
  15. <li>&nbsp;</li>  
  16. </ul>  
  17. </form>  
  18. </div>  
  19. <script src="phoneno-all-numeric-validation.js"></script>  
  20. </body>  
  21. </html>  

JavaScript Code

  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\d{10}$/;  
  4.   if(inputtxt.value.match(phoneno))  
  5.   {  
  6.       return true;  
  7.   }  
  8.   else  
  9.   {  
  10.      alert("Not a valid Phone Number");  
  11.      return false;  
  12.   }  
  13.   }  
View the example in the browser
Flowchart :
Flowchart : JavaScript - phone validation 10 digit

Validate North American phone numbers

Now, let's see how to validate a phone number, either in 222-055-9034, 321.789.4512 or 123 256 4587 format.

HTML Code

  1. <!DOCTYPE html><br><html lang="en"><br><head>  
  2. <meta charset="utf-8">  
  3. <title>JavaScript form validation - checking non-empty</title>  
  4. <link rel='stylesheet' href='form-style.css' type='text/css' />        
  5. </head>  
  6. <body onload='document.form1.text1.focus()'>  
  7. <div class="mail">  
  8. <h2>Input an Phone No.[xxx-xxx-xxxx, xxx.xxx.xxxx, xxx xxx xxxx] and Submit</h2>  
  9. <form name="form1" action="#">   
  10. <ul>  
  11. <li><input type='text' name='text1'/></li>  
  12. <li>&nbsp;</li>  
  13. <li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>  
  14. <li>&nbsp;</li>  
  15. </ul>  
  16. </form>  
  17. </div>  
  18. <script src="phoneno-international-format.js"></script>  
  19. </body>  
  20. </html>  

JavaScript Code

  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
  4.   if(inputtxt.value.match(phoneno))  
  5.      {  
  6.        return true;        
  7.      }  
  8.    else  
  9.      {  
  10.        alert("Not a valid Phone Number");  
  11.        return false;  
  12.      }  
  13. }  
View the example in the browser
Flowchart :
Flowchart : JavaScript - phone validation North America

Validate an international phone number with country code

Now, let's see how to validate a phone number with country code, either in +24-0455-9034, +21.3789.4512 or +23 1256 4587 format.

HTML Code

  1. <!DOCTYPE html><br><html lang="en"><br><head>  
  2. <meta charset="utf-8">  
  3. <title>JavaScript form validation - checking non-empty</title>  
  4. <link rel='stylesheet' href='form-style.css' type='text/css' />  
  5. </head>  
  6. <body onload='document.form1.text1.focus()'>  
  7. <div class="mail">  
  8. <h2>Input an Phone No.[+xx-xxxx-xxxx, +xx.xxxx.xxxx, +xx xxxx xxxx] and Submit</h2>  
  9. <form name="form1" action="#">   
  10. <ul>  
  11. <li><input type='text' name='text1'/></li>  
  12. <li>&nbsp;</li>  
  13. <li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>  
  14. <li>&nbsp;</li>  
  15. </ul>  
  16. </form>  
  17. </div>  
  18. <script src="phoneno-+international-format.js"></script>  
  19. </body>  
  20. </html>  

JavaScript Code

  1. function phonenumber(inputtxt)  
  2. {  
  3.   var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
  4.   if(inputtxt.value.match(phoneno))  
  5.      {  
  6.        return true;  
  7.      }  
  8.    else  
  9.      {  
  10.        alert("Not a valid Phone Number");  
  11.        return false;  
  12.      }  
  13. }  
View the example in the browser
Flowchart :
Flowchart : JavaScript - phone validation international

Friday, August 12, 2016

javascript stackoverflow

JavaScript (not to be confused with Java or Jscript) is a dynamic, weakly-typed language used for client-side as well as server-side scripting. Use this tag for questions regarding ECMAScript and its various dialects/implementations (excluding ActionScript and Google-Apps-Script). Unless another tag for a framework/library is also included, a pure JavaScript answer is expected.
JavaScript is a dynamic, object-based, duck-typed, prototype-based, weakly typed language traditionally used for client-side scripting in web browsers. can also be run outside of the browser with the use of a framework like , , , or . Despite the name, it is unrelated to the Java programming language and shares only superficial similarities.
Unless a tag for a framework or library is also included, a pure JavaScript answer is expected for questions with the tag.
JavaScript runs on nearly every Operating System, and an engine is included in mainstream web browsers. Developed in 1995 by Brendan Eich at Netscape Communications, it was originally called LiveScript but was renamed to JavaScript due to Netscape's friendly relationship with Sun Microsystems at the time.
Standalone JavaScript engines or interpreters are available as well, including:
  • Mozilla's , the first JavaScript engine ever written, currently used in Mozilla Firefox.
  • , Google's JavaScript interpreter, used in Google Chrome.
  • , a cloud-based / server-side interpreter that provides programmatic "macro-like" control of Google Apps services and documents.
  • , built on top of , a platform which enables server-side applications to be written in JavaScript.
  • Windows includes , a JavaScript variant in Windows Script Host.
  • Mozilla also offers , an implementation of JavaScript built in Java, typically embedded into Java applications to provide scripting to end users.
  • (except for the Chromium project) implements the engine.
  • (originally derived from HyperTalk) is now an ECMAScript dialect and uses a lot of ECMAScript APIs.
  • Embeddable, portable ECMAScript engine in C with small memory footprint.
  • a framework, IDE, and Server built on supporting server-side JavaScript
  • A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container. (according to MeteorJS docs )
The Mozilla Developer Network contains high-quality documentation on JavaScript.
JavaScript is typically used to manipulate the Document Object Model (DOM) and Cascading Style Sheets (CSS) within the browser. This allows user interface scripting, animation, automation, client-side validation, and much more.
With the recent emergence of platforms such as Node.js, JavaScript can now be used to write server-side applications. In addition, it is also used in environments that aren't web-based, like PDF documents, site-specific browsers, desktop widgets etc.

Nomenclature

Although it was developed under the name Mocha, the language was officially called LiveScript when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript when it was deployed in the Netscape browser version 2.0B3.
The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.
People often use the term JavaScript informally. The language and the term originated from Netscape. ECMAScript, JavaScript, and JScript are terms that are easy to confuse.
ECMAScript was developed as a standardization of Netscape's JavaScript and Microsoft's independently-developed JScript. The canonical reference is the ECMAScript® 2015 Language Specification. While JavaScript and JScript aim to be compatible with ECMAScript, they also provide additional features (and other deviations) not described in the ECMA specifications. Other implementations of ECMAScript also exist.
The differences today for those who use JavaScript are negligible; people generally do not distinguish the JavaScript and JScript variations from ECMAScript.

ECMAScript versions

Most modern browsers implement JavaScript based on the specification, although some fail to implement some ES6 features. However, older browsers such as Internet Explorer 8 implement the ECMAScript 3 specification, which does not contain functions such as Function.prototype.bind and even JSON.parse, amongst others.
The current version of ECMAScript is version 7 (), properly known as ECMAScript 2016, which was finalized in June 2016.

When asking a JavaScript question, you should:

  1. Debug your JavaScript code (see Creativebloq, MDN, Google, & MSDN).
  2. Isolate the problematic code and reproduce it in a Stackoverflow code snippet or an external online environment such as JSFiddle or JS Bin (remember to also include the code in the question itself).
  3. If a library or framework is used, then tag the question with the appropriate tags: for jQuery, for Prototype, for MooTools, and so on. However, if a framework is not used or necessary, do not include these tags.
  4. Mention which browser the code is having problems on, and what error messages, if any, were thrown by the browser (use the Developer Tools for your browser (see "Useful Tools" below) to see these messages). If the question is browser-specific, use tags , , , , , ,etc.
  5. Only tag the question as or if you are asking about an issue that concerns the combination of one of those with JavaScript and could only be answered with information specifically regarding either of those subjects.

Learning JavaScript

Security

JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the Web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform Web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the same origin policy: scripts from one Web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.
Content Security Policy is the main intended method of ensuring that only trusted code is executed on a Web page.

Useful Tools

Interactive JavaScript learning

Wisdom from the Stack

Useful links

Free JavaScript Programming Books

Videos


Example JavaScript code

This script displays "Hello World" on your screen.
window.onload = function() {
   alert('Hello World!');
}
Demo!

onload Event

Event Object Reference Event Object

Example

Execute a JavaScript immediately after a page has been loaded:
<body onload="myFunction()">

More "Try it Yourself" examples below.

Definition and Usage

The onload event occurs when an object has been loaded.
onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload event can also be used to deal with cookies (see "More Examples" below).

Browser Support

Event




onload Yes Yes Yes Yes Yes

Syntax

In HTML:
<element onload="myScript">
In JavaScript:
object.onload=function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("load", myScript);
Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

Technical Details

Bubbles: No
Cancelable: No
Event type: UIEvent if generated from a user interface, Event otherwise.
Supported HTML tags: <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
DOM Version: Level 2 Events

Examples

More Examples

Example

Using onload on an <img> element. Alert "Image is loaded" immediately after an image has been loaded:
<img src="w3javascript.gif" onload="loadImage()" width="100" height="132">

<script>
function loadImage() {
    alert("Image is loaded");
}
</script>

Example

Using the onload event to deal with cookies:
<body onload="checkCookies()">

<script>
function checkCookies() {
    var text = "";

    if (navigator.cookieEnabled == true) {
       text = "Cookies are enabled.";
    } else {
        text = "Cookies are not enabled.";
    }

    document.getElementById("demo").innerHTML = text;
}
</script>

JavaScript Where To



JavaScript can be placed in the <body> and the <head> sections of an HTML page.

The <script> Tag

In HTML, JavaScript code must be inserted between <script> and </script> tags.

Example

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Older examples may use a type attribute: <script type="text/javascript">.
This type attribute is not required. JavaScript is the default scripting language in HTML.

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "asked" for.
For example, a function can be executed when an event occurs, like when the user clicks a button.
You will learn much more about functions and events in later chapters.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
Keeping all code in one place, is always a good habit.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html><head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>
It is a good idea to place scripts at the bottom of the <body> element.
This can improve page load, because script compilation can slow down the display.

External JavaScript

Scripts can also be placed in external files:

myScript.js

function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is located.
External scripts cannot contain <script> tags.

External JavaScript Advantages

Placing JavaScripts in external files has some advantages:
  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

JavaScript HTML DOM - Changing CSS



The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style

To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:

Example

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Using Events

The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
  • An element is clicked on
  • The page has loaded
  • Input fields are changed
You will learn more about events in the next chapter of this tutorial.

Thursday, August 11, 2016

JavaScript HTML DOM


With the HTML DOM, JavaScript can access and change all the elements of an HTML document.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

DOM HTML tree
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can remove existing HTML elements and attributes
  • JavaScript can add new HTML elements and attributes
  • JavaScript can react to all existing HTML events in the page
  • JavaScript can create new HTML events in the page

What You Will Learn

In the next chapters of this tutorial you will learn:
  • How to change the content of HTML elements
  • How to change the style (CSS) of HTML elements
  • How to react to HTML DOM events
  • How to add and delete HTML elements

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
  • Core DOM - standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:
  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

JavaScript Form Validation


HTML form validation can be done by a JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

JavaScript Example

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}
The function can be called when the form is submitted:

HTML Form Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:
Please input a number between 1 and 10

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:

HTML Form Example

<form action="demo_form.asp" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>
Automatic HTML form validation does not work in Internet Explorer 9 or earlier.

Data Validation

Data validation is the process of ensuring that computer input is clean, correct, and useful.
Typical validation tasks are:
  • has the user filled in all required fields?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct input to a computer application.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.