JavaScript : Form and Validations

Forms are the primary means of giving information from the user. One of the original uses of JavaScript was to offl oad some form-processing responsibilities onto the browser instead of relying on the server to do it all. Although the Web and JavaScript
have evolved since that time, web forms remain more or less unchanged. Web forms are represented by the <form> element in HTML and by the HTMLFormElement type in JavaScript. The HTMLFormElement type inherits from HTMLElement and therefore has all of the same default properties as other HTML elements.

The <form> tag is used to create an HTML form for user input. Forms are submitted when a user interacts with a submit button or an image button. If any one of these types of buttons is within a form that has a submit button, pressing Enter on the keyboard while a form control has focus will also submit the form. (The one exception is a textarea, within which Enter creates a new line of text.) When a form is submitted in this manner, the submit event fires right before the request is sent to the server. This gives you the opportunity to validate the form data and decide whether to allow the form submission to occur. Preventing the event’s default behavior cancels the form submission.

Lets see a simple form with some basic validations. The form contains 3 input fields. These fields will be validated using javascript.


<!DOCTYPE html>
<html>
<head>
<title>Registration Basic</title>
</head>
<body>
<form name="myForm" action="" onsubmit="validateForm(event)"
autocomplete="off">

<table>
<tr>
<td>Name:</td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="txtAge" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="txtEmail" /></td>
</tr>
<tr>
<td><input name="btnReset" type="reset" value="Reset" /></td>
<td><input name="btnSubmit" type="submit" value="Submit" /></td>
</tr>
</table>

</form>
<script type="text/javascript">
function validateForm(event) {
var varForm = document.myForm;
var txtName = varForm.txtName;
var txtAge = varForm.txtAge;
var txtEmail = varForm.txtEmail;
var button = varForm.btnSubmit;
var age = parseInt(txtAge.value);

button.disabled = true;
if (!isEmpty(txtName.value)) {

// validate age
if (!isNaN(age) && age > 0) {

// validate email field
if (txtEmail.value.indexOf("@") > 0) {

return ;

} else {
alert("Please enter a valid email address");
txtEmail.focus();
txtEmail.select();
}

} else {
alert("Please enter your age");
txtAge.focus();
txtAge.select();
}

} else {
alert("Please enter your name");
txtName.focus();
}

button.disabled = false;
event.preventDefault();
}

function isEmpty(value) {
return (value === "");
}
</script>
</body>
</html>

The <form> tag has 4 attributes –name attribute – is used to reference elements in a JavaScript, or to reference form data after a form is submitted; autocomplete (HTML new addition) – Specifies whether a form should have autocomplete on or off ; action attribute -Specifies where to send the form-data when a form is submitted (For now its not setted, so it will try to hit the same url with GET parameters) ; onsubmit –  to call a JS function to validate.
Forms are reset when the user clicks a reset button. Reset buttons are created using either the <input> or the <button> element with a type attribute of “reset”. When a form is reset by the user clicking a reset button, the reset event fi res. This event gives you the opportunity to cancel the reset if necessary. As with form submission, resetting a form can be accomplished via JavaScript using the reset() method, as in this example:
var form = document.getElementById(“myForm”);
//reset the form
form.reset();

Notice that in the input tags we are using ‘name’ and not ‘id’. Id is used to identify the HTML element through the Document Object Model (via Javascript or styled with CSS). Id is expected to be unique within the page. Name corresponds to the form element and identifies what is posted back to the server.  For example, you may have several radio buttons with different ids, but the same name. When submitted, there is just the one value in the response – the radio button you selected.

In the validateForm() js method, we got the form element in var using document.myform. Using this we got other element (not their values).
One of the biggest issues with form submission is the possibility of submitting the form twice. Users sometimes get impatient when it seems like nothing is happening and may click a submit button multiple times. The results can be annoying (because the server processes duplicate requests) or damaging (if the user is attempting a purchase and ends up placing multiple orders). There are essentially two ways to solve this problem: disable the submit button once the form is submitted, or use the onsubmit event handler to cancel any further form submissions. Therefore we disabled the submit button while performing validation.

For better user experiance we used focus() and select(). focus() will focus the entire field while select() will select the input in that field (for deleting at once or copying etc)

Notice that there are many if/else and for a large form it will be tedious to follow such practice. Before changing lets see javascript try-catch syntax:

try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}

The throw statement lets you create custom errors, actually it could be any type of object. Changing the javascript in above:


function ValidationException(element, message) {
this.element = element;
this.message = message;
}

function validateForm(event) {
var varForm = document.myForm;
var txtName = varForm.txtName;
var txtAge = varForm.txtAge;
var txtEmail = varForm.txtEmail;
var button = varForm.btnSubmit;
var age = parseInt(txtAge.value);

button.disabled = true;

try {
if (isEmpty(txtName.value)) {
throw new ValidationException(txtName,"Please enter your name.");
}

if (isNaN(age) || !(age > 0)) {
throw new ValidationException(txtAge,"Please enter a valid age.");
}

if (!(txtEmail.value.indexOf("@") > 0)) {
throw new ValidationException(txtEmail,"Please enter a valid email address.");
}
} catch (exception) {
var element = exception.element;

alert(exception.message);
element.focus();
element.select();

event.preventDefault();
button.disabled = false;
}
}

function isEmpty(value) {
return (value === "");
}

As you can see, we created a dataype (ValidationException) to represent a type of errors for us which has the information about the element whse validation failed and the message which we want to show to the user. We have our validation inside of try. catch can also be assumed as a function having ts own level of scope. ‘exception’ argument inside the catch is used to catch the exception object thrown by ‘throw’ keyword or internal error. Using this approach makes code more readable and manageble

Difference between GET and POST methods?

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource
GET POST
BACK button/Reload Harmless Data will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
Bookmarked Can be bookmarked Cannot be bookmarked
Cached Can be cached Not cached
Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
History Parameters remain in browser history Parameters are not saved in browser history
Restrictions on data length Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) No restrictions
Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also allowed
Security GET is less secure compared to POST because data sent is part of the URLNever use GET when sending passwords or other sensitive information! POST is a little safer than GET because the parameters are not stored in browser history or in web server logs
Visibility Data is visible to everyone in the URL Data is not displayed in the URL

You could use a GET request to do pretty much the same thing as a POST query. It’s just that browsers are generally coded to expect that POST requests will be used for things that will cause changes – like placing an order, or writing to a database, etc . GET requests should be used for pure queries that don’t affect anything on the server.

 Difference between XHTML,HTML,DHTML

HTML is a Hyper Text Markup Language which is used to display the internet website contents on the internet browsers. This is the common language to develop the web site pages.
XHTML is similar to the HTML but follows the rules of XML.  XHTML is a W3C standard.  It is not difficult to change HTML pages to XHTML, but it can be time-consuming. The main differences between HTML and XHTML is the case-sensitivity, the need to use closing tags for all tags, the need to use quotes around all attribute values and that all attributes must be in lowercase as XML requires.
DHTML is Dynamic HTML(DHTML) which will be used to display the dynamic web site pages. It is not a standard defined by the W3C. Nobody really talks in terms of DHTML any more

DocType and DOM

DOM – API for HTML. It represents a web page as a tree. In other words, DOM shows how to access HTML page.

DOCTYPE is used

  • for validation, “validator.w3.org”
  • specifies the version of HTML. If doctype is omitted, browser renders a web page in quirks mode. Quirks mode emulates behavior of old browsers (old box model).

The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag. The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. For example:

  • HTML 5
    <!DOCTYPE html>
  • HTML 4.01 Strict
    This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.
    <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN” “http://www.w3.org/TR/html4/strict.dtd”&gt;
  • HTML 4.01 Transitional
    This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed.
    <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;
  • etc …

What are meta tags and why it is used?

Metadata is data (information) about data. The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable. Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata. The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.

<head>
<meta charset=“UTF-8”>
<meta name=“description” content=“tutorials”>
<meta name=“keywords” content=“Java,JavaScript”>
<meta name=“author” content=“Dhananjay”>
</head>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: