basic Javascript email validation

This function will check for very basic user mistakes such as @ sign and .com and stuff.

// function to validate email address
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
// end email address validator

Use it like this in your code where ever you need it….

if (validateEmail(student_class_instructor_email) == false) {alert(“Error, please check the instructor email address for proper syntax.”); return false;}

 

a really bad ass way to display the error alert , especially in foundation, is to change the alert() to a prepend of the form or even the element that had the error…

alert(“Error…)
$(‘#foundationform’).prepend(“Error, please check the  email address for proper syntax.”);

if you have foundation you can use the error box built in with a close button .. just wrap it around the error message

<div class=’alert-box alert’>Error, please check the  email address for proper syntax.<a href=” class=’close’>&times;</a></div>

Loop through form elements with Javascript using modern form validation techniques.

Here are some techniques that I use to loop through a form , access the elements and validate the field.

Here is one that will look for any field with an id, and require it. Then it will display the error message using the label of the field. sick!

function checkForm() {
        // begin basic form validation
        // check for empty fields name. adress etc.
        var str = '';
        var elem = document.getElementById('golf_reg_form').elements;
        for(var i = 0; i < elem.length; i++)
        {
           if(elem[i].value=="" && elem[i].id!==""){
            var myelem = elem[i];
            dalabel = $( elem[i] ).prev().html();
            alert("Please fill in  " + dalabel);
            //$( elem[i] ).val("error");-- note "A"
            return false;
            } 

        } 

    } // end form validation funk

note “A”: — here is where you could set some responsive disclosure ui features to help user know where the error is.

<script type="text/javascript">
    function DisplayFormValues()
    {
        var str = '';
        var elem = document.getElementById('frmMain').elements;
        for(var i = 0; i < elem.length; i++)
        {
            str += "<b>Type:</b>" + elem[i].type + "&nbsp&nbsp";
            str += "<b>Name:</b>" + elem[i].name + "&nbsp;&nbsp;";
            str += "<b>Value:</b><i>" + elem[i].value + "</i>&nbsp;&nbsp;";
            str += "<BR>";
        } 
        document.getElementById('lblValues').innerHTML = str;
    }
</script>

Update: I have figured out how to access this elem[i] using jquery.

$( elem[i] ).val(“error”);

Here is how to remove the error display when the user begins to correct it.
// this is to remove an error message after the user corrects it.
function typeIn(i, a)  {

if (document.sports_recruitment_form.elements[i].className==”error”) {

document.sports_recruitment_form.elements[i].className = ” “;

}

Then I can use selectors and apply the event handler to required fields: onclick=”typeIn(this.name, this.value)”

I could use jquery to loop through the form if I wanted to have more precision selectors like choosing only checkboxes, or even only checked checkboxes.

 

Here is a great example of how to select inputs from a large form, all elements have been named in groups, and setting each one with a unique id would be a waste of time.Instead, just give the container a unique id, and then access the child elements using jquery’s powerful selectors.

<div class=”six columns disclose” id=”golfer1″>

<label>First</label><input name=”team” type=”text” size=”24″/>

<label>Last</label><input name=”team” type=”text” size=”24″  />

<label>Email</label><input name=”team” type=”text” size=”40″ />

<label>Phone</label><input name=”team” type=”text” size=”16″ />

</div>

for(var allfields=0; allfields<=$(“#golfer1 :input”).length-1;allfields++){
alert($(“#golfer2 input:eq(“+allfields+”)”).val());
}

 

This code will loop through and detect the value of any input elements within the parent container. From there we could create some validation or whatever we want to do with the data.

UPDATE: after years of practice, I have concluded that the name and id should be set as so: <label>Phone</label><input name=”Phone Number” type=”text” id=”phone” size=”16″ /> then the labels and/or placeholders could be created dynamically from the name.

// set the placeholder of every text input to equal its name attribute
$(“form :input[type=’text’]”).each(function(){
$( this ).attr(“placeholder”, $( this).attr(“name”));
});

Managing Persistent Data In Your Web Applications Using DOM Storage

The 90’s saw many inovations in the web, but not much changed in the way of client side storage. Javascript and cookies were the way to keep user data saved in the browser.

Recently various techniques for storing and retrieving data have emerged. There are so many different ways in fact that we need to answer some questions to determine the best solution for persisting data between requests.

We have to ask who needs the data ? How long does the data need to be persisted?  And how large is the set of data?

Persistence Method Who Needs the Data? For How Long? How Much Data?
Application All users Until the next application restart Can be almost any size—it will only be stored once
Cookie One user As short as desired, or for months or even years if the user doesn’t delete their cookies Minimal, simple data
Form Post One user For the next request (can be reused across many requests) Virtually any size—the data is sent back and forth with every page
QueryString One user or one group of users For the next request (can be reused across many requests) Minimal, simple data
Session One user As long as the user is active, plus a timeout period (typically 20 minutes) Can be almost any size, but should be minimized since every user has their own separate session store
Cache All users or a subset of users As long or as short as needed Can be used for large or small, simple or complex data
Context One user This request only Can hold large objects, but typically does not since it is often used for every request
ViewState One user One Web form Minimal; as with Form Post, this data is sent back and forth with every page
Config file All users Until the configuration file is updated Can hold a lot of data; usually organized as many small strings or XML structures

Application

Let’s set the object use criteria by answering the state questions I asked earlier. Who needs this data? All users need access to it. How long does this data need to be persisted? It has to live forever, or for the life of the application. How large is this data? It can be almost any size—only one copy of the data will exist at any given time.
In classic ASP, the Application object provided a great place to store frequently used pieces of data that changed infrequently, such as the contents of menus or other reference data. While the Application object is still available as a data container in ASP.NET, other objects are generally better suited for the kinds of data that would have been stored in the Application collection of a classic ASP application.
Cookies

Cookies are handy when a particular user needs a specific piece of data, and it needs to be persisted for a variable period of time. It can be as brief as the life of the browser window, or as long as months or even years. As far as size goes, cookies are very small. Cookies can be as small as only a few bytes of data, and since they are passed with every browser request, their contents should be kept as small as possible.
Security NOTE : The best way to secure sensitive state that should not be viewed or modified by a hostile user is to store that state on the server. If sensitive data must be sent to the client, it should be encrypted beforehand, regardless of the storage mechanism employed.
Form Post / Hidden Form Field

Form data is needed by a particular user, and it must be persisted for any period from a single request to the life of the application. The data can be virtually any size; it’s sent back and forth over the network with each form post. This requires the data to be sent back and for to each other using Submit buttons, or saved on the client machine with cookies.  This was a classic technique that is not recommended anymore.
QueryString

The data stored in the QueryString object is used by the individual user. Its lifetime can be as brief as a single request, or as long as the user continues to use the application (if architected appropriately). This data is typically less than 1KB. Data in a QueryString is passed in the URL and is visible to the user, so as you might guess, sensitive data or data that can be used to control the application should be encrypted when using this technique.
That said, the QueryString is a great way to send information between Web forms in ASP.NET. For example, if you have a DataGrid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the QueryString to include the product ID in the QueryString of the link to the product details page (for example, productdetails.aspx?id=4). Another advantage of using QueryStrings is that the state of the page is contained in the URL. This means that a user can put a page in their Favorites folder in its generated form when it’s created with a QueryString. When they return to it as a favorite, it will be the same as when they actually made it a favorite. Obviously, this only works if the page doesn’t rely on any state outside the QueryString and nothing else changes.
Along with sensitive data, any variable that you don’t want the user to be able to manipulate should be avoided here (unless encryption is used to remove human-readability). Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode, as Figure 7 shows. When dealing with a single ASP.NET page, ViewState is a better choice than QueryString for maintaining state. For long-term data storage, Cookie, Session, or Cache are more appropriate data containers than QueryStrings.

Session

Session data is specific to a particular user. It lives for as long as the user continues to makes requests plus some period of time afterward (typically 20 minutes). The Session object can hold large or small amounts of data, but total storage should be kept minimal if the application is intended to scale to hundreds of users or more.
Using the Session object is easy and its syntax is identical to classic ASP. However, the Session object is one of the less efficient ways of storing user data, since it is held in memory for some time even after the user has stopped using the application. This can have serious effects on scalability for a very busy site.
For small amounts of data, the Session object can be a perfectly valid place to store user-specific data that needs to persist only for the duration of the user’s current session.
This sounds like the way to go for my progress reporting application. So, lets dive into a demo and see how we can save some data in session object.

Here is some sample session variable code: Methods

Create session variable and set it:

Session(“varName”) = varValue

 

Get on page:

newVar = Sesssion(“varName”)

 

Clear session variable:

Session(“varName”) = “” OR

Session.Contents.Remove(“varName”)

Clear out session when done:

Session.Contents.RemoveAll()    OR

Session.Abandon

I would combine the two to ensure that pesky session data is gone.My logout script is :

Session.Contents.RemoveAll()
Session.Abandon
Response.Redirect(“default.asp”)

The session object has the onStart and OnEnd events and the SessionID and Timeout properties

 

A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. They could need longer for filling out these forms.

If you want to set a timeout interval that is shorter or longer than the default, use the Timeoutproperty.

Session.Timeout=5 gives the session 5 minutes of inactivity. I think you would want a few hours at least.

 

 

Here is the best resources for asp dev http://www.w3schools.com/asp/asp_sessions.asp

http://www.tizag.com/aspTutorial/aspSession.php

This is a summary of a microsoft developer network article. that was updated in 2005.

 

 

Now lets get into the new technology

Here is my personal test file http://itwebdev.mv.skagit.edu/don/stuff/dom%20storage/domstorage.html

DOM storage, also called Web Storage is comprable to cookies. However, web storage offers more control of  how the information is stored and accesed by each window.

This technique also offers a lot more storage space, and quite different functionality than cookies.

 

The web storage scripting objects have been drafted into the HTML 5 working draft specifications, and have gathered major vendor support.

window.sessionStorage
Session storage is designed for scenarios where the user is carrying out a single transaction. The sessionStorage attribute of the window object maintains key/value pairs for all pages loaded during the lifetime of a single tab (for the duration of the top-level browsing context). For example, a page might have a check box that the user selects to indicate that he wants insurance. A later page could then check, from script, whether the user had selected the check box.

The Storage object supports expando properties (‘insurance’ in the preceding example). If the property name does not exist, a key/value pair is automatically created to hold it. Note that key/value pairs are always stored as strings. Different data types such as numbers, Boolean values, and structured data must be converted to strings before persisting to a storage area.

After a value has been saved to sessionStorage, it can be retrieved by script running in another page in the same context. When another document is loaded,sessionStorage is initialized from memory for same-origin URLs

Note  Although it is allowed by the HTML5 (Working Draft), Internet Explorer 8 does not resume sessionStorage after browser crash recovery.

 

window.localStorage

The local storage mechanism spans multiple windows and persists beyond the current session. The localStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user’s mailbox, on the client for performance reasons.

here is the msdn article that this blog post sumarrizes http://msdn.microsoft.com/en-us/library/cc197062(v=vs.85).aspx

 

 

Google Web Fonts

An exciting addition to web development arsenal is the Google Web Fonts api. The problem with fonts onthe web was that many computers dont have the same fonts, as they vary from system to system. http://www.google.com/webfonts

Elaborate on this, do some demos and release the post.

 

They say to start by choosing some fonts to add to a collection, then you dl the files.

The interface for choosing fonts is great. you can sort and filter the fonts depending on what you need for your project.Then you add them to a collection with the touch of a button.

Serifs, the tiny decorations on the tips of the letters, usually dont work well on screens, so they dont get used on webpages as often as sans. I am going to build a collection of serif fonts that look good onthe screen, so I can use them on some pages.

Well after i finished building a collection, they say that using too many will impact page load times. You should only choose the one or two you want for your web page.There is a cool web page load time meter that will show you if you have chosen too many fonts.So, I uncheck ed the boxes until i was left with my favorite two fonts, and they don’t have a huge impact on load  time.

Then, just add this link to your document  <link href=’http://fonts.googleapis.com/css?family=Metamorphous|Cagliostro’ rel=’stylesheet’ type=’text/css’>

Lastly, just add the font to a style statement like this example:

Example:

h1 { font-family: ‘Metamorphous’, Arial, serif; font-weight: 400; }

Creating a single-use required response interactive form

Vote Registration Prompt

I need to make a 1 time use required interactive prompt.  part of web assistant duties state compliance issue.

This will require..

content container.

Place the content into a div container. Give it a unique id, and set it’s  display:none.

<div  id=”myprompt”  style=”display:none” >Here is my exciting and important content. It needs your response.This will interrupt your user flow until you respond.</div>

This is in mysvc.asp

external styling.

I make a custom style for the div container give it a good location, and  to make it look important. Style the top, left, width, height, borders text  and background to match the theme.

This is a style defined  in mysvcdb.css as promptstyle.

interactive response form.

This is the content for the prompt. It is a question that needs a response, the best use for a web form, no? Make a standard web form for now. In the content container in mysvc.asp

Asp  form capture logic.

This will be the logic to capture the user response to the form. you can use your flavor of server side languages. Im using classic asp here. Benjy whipped this up and i made a few changes

The file is votereg.asp

Javascript Logic

to Show and hide the content based on the user interaction.

Storage of user interaction results

So no repeat. Could use  user request.cookie…dom storage … User preference database storage.

Logic to check user compliance to requirements at login.

check cookie or db storage for compliance.

Changing an objects class to create functionality and cool effects

There are some great uses for changing an objects class via script. One of them is form elements. To create a better user experience, and guide them through the form, we can change the elements based on classes to show, hide and highlight the path way for the user.

To add a class to an element:

document.getElementById("MyElement").className += " MyClass"; 

To remove a class from an element:

document.getElementById("MyElement").className =    document.getElementById("MyElement").className.replace       ( /(?:^|s)MyClass(?!S)/g , '' ) /* code wrapped for readability - above is all one statement */ 

To do that in an onclick event:

<script type="text/javascript">     function changeClass()     {         // code examples from above     } </script> ... <button onclick="changeClass()">My Button</button> 

 

Better yet, use a framework (in this example jQuery) which allows you to do the following:

$j('#MyElement').addClass('MyClass'); $j('#MyElement').removeClass('MyClass'); $j('#MyElement').toggleClass('MyClass'); 

And also:

<script type="text/javascript">     function changeClass()     {         // code examples from above     }     $j(':button:contains(My Button)').click(changeClass); </script> ... <button>My Button</button>