Friday, 8 April 2016

JavaScript Form Validation

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>

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>

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.

HTML Constraint Validation

HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
  • Constraint validation HTML Input Attributes
  • Constraint validation CSS Pseudo Selectors
  • Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

AttributeDescription
disabledSpecifies that the input element should be disabled
maxSpecifies the maximum value of an input element
minSpecifies the minimum value of an input element
patternSpecifies the value pattern of an input element
requiredSpecifies that the input field requires an element
type Specifies the type of an input element
For a full list, go to HTML Input Attributes.

Constraint Validation CSS Pseudo Selectors

SelectorDescription
:disabledSelects input elements with the "disabled" attribute specified
:invalidSelects input elements with invalid values
:optionalSelects input elements with no "required" attribute specified
:requiredSelects input elements with the "required" attribute specified
:validSelects input elements with valid values

CSS Backgrounds


The CSS background properties are used to define the background effects for elements.
CSS background properties:
  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

Background Color

The background-color property specifies the background color of an element.
The background color of a page is set like this:

Example

body {
    background-color: lightblue;
}
With CSS, a color is most often specified by:
  • a valid color name - like "red"
  • a HEX value - like "#ff0000"
  • an RGB value - like "rgb(255,0,0)"
Look at CSS Color Values for a complete list of possible color values.
In the example below, the <h1>, <p>, and <div> elements have different background colors:

Example

h1 {
    background-color: green;
}

div {
    background-color: lightblue;
}

{
    background-color: yellow;
}

Background Image

The background-image property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element.
The background image for a page can be set like this:

Example

body {
    background-image: url("paper.gif");
}
Below is an example of a bad combination of text and background image. The text is hardly readable:

Example

body {
    background-image: url("bgdesert.jpg");
}
NoteNote: When using a background image, use an image that does not disturb the text.

Background Image - Repeat Horizontally or Vertically

By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like this:

Example

body {
    background-image: url("gradient_bg.png");
}
If the image above is repeated only horizontally (background-repeat: repeat-x;), the background will look better:

Example

body {
    background-image: url("gradient_bg.png");
    background-repeat: repeat-x;
}
NoteNote: To repeat an image vertically set background-repeat: repeat-y;

Background Image - Set position and no-repeat

Showing the background image only once is also specified by the background-repeat property:

Example

body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
}
In the example above, the background image is shown in the same place as the text. We want to change the position of the image, so that it does not disturb the text too much.
The position of the image is specified by the background-position property:

Example

body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
    background-position: right top;
}

Background Image - Fixed position

To specify that the background image should be fixed (will not scroll with the rest of the page), use the background-attachment property:

Example

body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
    background-position: right top;
    background-attachment: fixed;
}

Background - Shorthand property

To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.
The shorthand property for background is background:

Example

body {
    background: #ffffff url("img_tree.png") no-repeat right top;
}
When using the shorthand property the order of the property values is:
  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position
It does not matter if one of the property values is missing, as long as the other ones are in this order.


All CSS Background Properties

PropertyDescription
backgroundSets all the background properties in one declaration
background-attachmentSets whether a background image is fixed or scrolls with the rest of the page
background-colorSets the background color of an element
background-imageSets the background image for an element
background-positionSets the starting position of a background image
background-repeatSets how a background image will be repeated

JavaScript Functions

 JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

Example

function myFunction(p1, p2) {
    return p1 * p2;              // The function returns the product of p1 and p2}

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:(parameter1,  parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
    code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments behave as local variables.
NoteA Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:
  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

Example

Calculate the product of two numbers, and return the result:
var x = myFunction(43);        // Function is called, return value will end up in x
function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b}
The result in x will be:
12

Why Functions?

You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.

Example

Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Example

Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Functions Used as Variables

In JavaScript, you can use functions the same way as you use variables.


Example

You can use:
var text = "The temperature is " + toCelsius(77) + " Celsius";
Instead of:
var x = toCelsius(32);
var text = "The temperature is " + x + " Celsius";

Creating the Web Application

f you have Visual Web Developer installed, start Visual Web Developer and selectNew Project. Otherwise just read and learn.
New Project
In the New Project dialog box:
  • Open the Visual C# templates
  • Select the template ASP.NET MVC 3 Web Application
  • Set the project name to MvcDemo
  • Set the disk location to something like c:\w3schools_demo
  • Click OK
When the New Project Dialog Box opens:
  • Select the Internet Application template
  • Select the Razor Engine
  • Select HTML5 Markup
  • Click OK
Visual Studio Express will create a project much like this:
Mvc Explorer