sign up! Channels Courses
 

Xan Chin Xao Ju - MrBool Space


20 last updates Xan Chin Xao Ju

Article - Creating your own Form Validation Plugin with JavaScript

Some of us have used a plugin to validate their form before submitting it. But it seems like that we don’t know enough how the field validation works. That’s why I’ve decided to talk about form validation today. Willing to show the way it works and if you go further, you can create your own form validation plugin, using regular expressions to test the user inputs.

Here is the picture of our article:

img1

Explanation:
  • While the user is entering the text, we show him explanation text in green;
  • We also test if his input is correct, if not, we show an error message in red;
  • We also use regular expressions to test if the typed value matches a given pattern

Html Code. Put this in FormValidationJS.htm file

[CODE] <!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <title>Form validation!!!</title> <link"formValidationJS.css"rel="stylesheet"type="text/css"/> <scriptsrc="jquery.1.7.2.js"type="text/javascript"></script> <scriptsrc="formValidationJS.js"type="text/javascript"></script> </head> <body><p> </p> <center> <formaction=''id='newUserForm'method="post"enctype="multipart/form-data"> <divclass='field'> Your Full Name<br/> <inputid="fullname"name="fullnameVar"type="text"class="input"/><br/> <divclass='report'> <labelid="fullname_info"class='info'>type your name(s) four words or less</label><br/> <labelid="fullname_error_message"class='error'>Your name must be alpha-numeric and not null. Please check and correct this value</label> </div> </div> <divclass='field'>Your email<br/> <inputid="email"name="emailVar"type="text"class="input"/> <divclass='report'> <labelid="email_info"class='info'>will help us to contact you back!<br/></label> <labelid="email_error_message"class='error'>Ooops! this email is not valid</label> </div> </div> <divclass='field'>Choose a password<br/> <inputid="password"name="passwordVar"type="password"class="input"/> <divclass='report'> <labelid="Label3"class='info'>your secret word <br/></label> <labelid="Label4"class='error'>This password is not enough strong! combine with a number please</label> </div> </div> <divclass='field'>Retype your password<br/> <inputid="password2"name="passwordVar2"type="password"class="input"/> <divclass='report'> <labelid="password2_info"class='info'>we want to check if you'll surely never forget this password<br/></label> <labelid="password2_error_message"class='error'>Oops! How come you forgot your pass only now? The two passwords must match. please check again</label> </div></div> <divclass='field'>A picture of you :)<br/> <inputid="picture"name="pictureVar"type="file"class="input"/> <divclass='report'> <labelid="picture_info"class='info'>Want to see your pic<br/></label> <labelid="picture_error_message"class='error'>This field is required</label> </div></div> <divclass='field'>Your birth date<br/> mm   /   dd   /   yyyy<br/> <inputid="month"name="monthVar"type="text"class="input_40"/>  <inputid="day"name="dayVar"type="text"class="input_40"/>  <inputid="year"name="yearVar"type="text"class="input_40"/>  <divclass="report"> <labelid="birthdate_info"class='info'>Share your birthday and age with us please<br/></label> <labelid="birthdate_error_message"class='error'>Ooops! This date is not valid. Please correct it</label> </div></div> <p> <inputtype="submit"value="Register Now"/> </p> </form></center> </body> </html> [/CODE]

Look inside the head tag:

[CODE]<link"formValidationJS.css"rel="stylesheet"type="text/css"/> <scriptsrc="jquery.1.7.2.js"type="text/javascript"></script> <scriptsrc="formValidationJS.js"type="text/javascript"></script> [/CODE]

You will need three more files:

  • A cascading style sheet named formValidationJS.css to design (or beautify) your html page with colors and so on.
  • jquery.1.7.2.js The jQuery library: downloadable on jQuery website. I’m using the 1.7.2 version, which is the last released;
  • And the validation code file, written in JavaScript-and-jQuery. The name of this file is formValidationJS.js

Here is the cascading style sheet:

[CODE] *{margin:0auto; padding:0auto; font-family:Arial} .left{float:left} .right{float:right} .clear{clear:both} .error{color:Red; display:none; font-family:Verdana; font-size:80%;} .report{min-height:20px;} .info{color:#383;display:none;font-family:Verdana; font-size:80%;} .none{border:none; background:none; list-style:none} input[type='text'],input[type='password']{border:1pxsolid#ccc; height:20px;width:220px; background:#efefef; color:#363;} input[type='file']{border:none; line-height:26px;width:220px; background:#efefef; color:#363;} input[type='submit']{border:1pxsolid#fff;background:#3366a9;color:White;padding:3px10px;} input.input_40{width:40px;} .borderable_box{border:1pxsolid#ccc;} input.gray_bg{background:#efefef} input.red_bg{background-color:#fcc} [/CODE]

Nothing to explain here, we only want to color our input field and their error messages…

Validation Code File

Onfocus()

Each time a field receives the focus, we want to show instructions that are inside the .info element and that was hidden via CSS. Here is how to do it.

[CODE] //-----On focus, show info $('div.field').each(function () { var _block = $(this); _block.find('input').focus(function () { var _input = $(this); _block.find('.info').fadeIn(300); }).focusout(function () { _block.find('.info').fadeOut(100); }); }); [/CODE]

Validating the name

A name can’t contain a number, a special char or a symbol. In addition, the full name must be at list 3 characters long! We also allow names consisting of one to four words. A name like ‘Xian Chin XiaoJu’ is allowed, the same than ‘Mark Zuckerberg’ or ‘Ricardhino’. But you can’t type a long name like: ‘Foo Bar Gentle Richard Sergio’ thereis five words and this will not be validated. A friend of mine used to cut his name ‘ASENGO JEI’ in ‘As’, this will not work because the word‘As’ has less than three letters.

Here is the code to validate the name:

[CODE]//------------validate name varfullNameObject = formObject.find('#fullname'); fullNameObject.keyup(function () { var me = $(this); varmyValue = me.val(); varmeError = false; meError |= myValue == null || typeofmyValue == undefined; meError |= (myValue.split(' ') != null) ? myValue.split(' ').length > 4 : false; //more than 4 words ? var pattern = /^([a-zA-ZÀ-ÿ\s]{3,})$/; varexpr = newRegExp(pattern); meError |= !(expr.exec(myValue)); if (meError) { me.addClass('red_bg'); me.parents('div.field').find('.info').fadeOut(100); me.parents('div.field').find('.error').fadeIn(300); } else { me.removeClass('red_bg'); me.parents('div.field').find('.error').fadeOut(100); } errorOccured = meError; }); //-----------end [/CODE]

There is a regular expression!!! Let me explain it:

[CODE] var pattern = /^([a-zA-ZÀ-ÿ\s]{3,})$/; varexpr = newRegExp(pattern); meError |= !(expr.exec(myValue)); [/CODE]
  • ^ means that a name must begin and
  • ($) means that it must end with a set of chars in parentheses,
  • [a-zA-ZÀ-ÿ\s]{Alphabetical letters, from a toz including lower and uppercase. Some European name such as Portuguese, French,
  • Spanish names have accents over vowels. That’s why I added the area from À to ÿ. Finally, I ...
Post view interrupted. To view full content, click here
5/16/2012 10:44:00 PM





Article - Localizable/Globalizable Attributes in ASP.NET

Think you have a localized asp.net mvc application; you also need to localize your attributes to completely satisfy your visitors. Yeah! Here is a simple class that you can add into your models folder in other to use a [GlobalizableAttributes] attribute over your models properties.

So, let’s see briefly what we’re going to see in detail :

  1. Creating a Localizable attribute class
  2. How to use our new created attribute
  3. Handling errors and exceptions as well

Pre-requisites

To follow this lesson, you must:

  • Have MS Visual Studio 2010
  • be good with data annotations; if not start here or learn more
  • Have a localized application. If you don’t know how to create a localizable application, follow this other tutorial. I appreciate the good job of this author, thx guy ;)

If you are ready, let’s go !

Creating a Localizable attribute class

The first thing we will do is creating a LocalizableAttribute class. An attribute class is a simple class that inherits from the dotnet Attribute class. But in this tutorial, our class will inherit from the DisplayNameAttribute class because what we want to do is not difference than what this class does, except the fact that we need our attributes to be localizable.

Here is that famous class

[CODE] using System; usingSystem.ComponentModel; usingSystem.ComponentModel.DataAnnotations; namespaceLocalizableAttributes.Models { publicclassGlobalizableAttributes : DisplayNameAttribute { privateDisplayAttribute display; privatestring _resource; publicGlobalizableAttributes(TyperesourceType, stringresourceName) { this.display = newDisplayAttribute() { ResourceType = resourceType, Name = resourceName }; this._resource = resourceName; } publicoverridestringDisplayName { ...
Post view interrupted. To view full content, click here
4/26/2012 8:44:00 PM





Article - All in One - Actions in MVC3


Introduction

I am talking about the ability to write an action that can serve both Ajax requests and non-Ajax request. Instead of writing many actions for each type of the request, you can use the following technic, the AllInOneAction as I call it.

In today’s lesson, we are going to see how an action can:

  • Return a partial view if the request is simply an Ajax request;
  • Return a jSon object view if the request is an Ajax requestthat expects a json result (for a mobile user interface for example);
  • Return a View in other cases.

In addition, we will learn:

  • A pagination technic.
  • How to handle errors and exceptions as well.

Pre-requisites

To follow this lesson you must be good with:

  • Basics in Asp.net mvc 3
  • Visual studio 2010

Let’s go to the example!

Step1. Create a new Project

img1

Step2. Add a controller named: ‘AllInOneController’

img2

Step3. Add this class in the ModelDirectory

[CODE] using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AllInOneActions.Models { public class StudentModel { public long studentId{ get; private set;} public string FirstName {get; set;} public string LastName {get; set;} public DateTime BirthDay {get; set;} public StudentModel(){} public StudentModel(long sId){ this.studentId=sId; } public static List<StudentModel> LoadStudents(){ List<StudentModel> students = new List<Models.StudentModel>(); StudentModel student; for(long i = 1; i <= 10; i++){ student = new StudentModel(i); student.FirstName = "FName"+i.ToString(); student.LastName = "LName" + i.ToString(); student.BirthDay = DateTime.Now.AddYears(-20); student.Add(student); } return students; } [/CODE]

Note: to stay simple, we use this class instead of using a database. But it in your case, you can use any model class, even an entity framework. Given you pay attention to avoid circular reference (to avoid the circular reference, please see the solution below).

Step4. Let’s go back into our AllInOneController, take the Index action. Think this action is destined to return a paginated list of students. Here is the way I code:

[CODE] // GET: /AllInOne/ publicActionResult Index(int? i, int? n) { try{ var Students = AllInOneActions.Models.StudentModel.LoadStudents() .Skip(i ?? 0) .Take(n ?? 4); if (Request.IsAjaxRequest()){ if (Request.Params["json"] != null){ int page = i ?? 0; int count = n ?? 4; varjSonObject = new{ paginationIndex = page, count = count, error=false, datas = Students }; returnJson(jSonObject,"text/json",JsonRequestBehavior.AllowGet); } returnPartialView("IndexPartial", Students.ToList()); } return View(Students.ToList()); }catch (Exception ex){ string message = "Sorry! an exception occured : " + ex.Message; if (Request.IsAjaxRequest()){ if (Request.Params["json"] != null){ varjSonObject = new{ error = true, Message = message }; returnJson(jSonObject); } ViewBag.Message = message; returnPartialView("NoticePartial"); } ViewBag.Message = message; return View("NoticePartial"); } } [/CODE]

Explanation:

[CODE] publicActionResultIndex(int? i, int? n){ [/CODE] The index action has two params that can be NULL that’s why I’ve written int? i instead of int i. Further in this code, you can find this notation [CODE] var Students = AllInOneActions.Models.StudentModel.LoadStudents() .Skip(i ?? 0) .Take(n ?? 4); [/CODE]

In this code, the LoadStudents returns a list of students. This list can have many items, for example 200000 students. This can of request will take too much time. That’s why I take a limit of n ite ...

Post view interrupted. To view full content, click here
4/20/2012 12:10:00 AM





Article - jQuery to extend the ActionLink

Note: Do not put all the code in the article, to see the entire code, download the complete source code of this article in this LINK, it's very important to make this example.

Think you have created a new asp.net mvc application.

In your master page your menu looks like this:

Imagem 1

Make it look like this

Imagem 1

Here is the code

[CODE] ...
Post view interrupted. To view full content, click here
4/13/2012 3:49:00 PM





 

xanchinxaoju@gmail.com

C# 4.5 Developer ASP.NET 4.5, Php 5, JavaScript (jQuery 1.6), Silverlight 4 (Sooner Beta5) xHtml, html5 Css 3 PhotoShop CS3 Java
Archive updates
 2012

Stats:
Total posts: 4
What people think:
Technical content:
People learning:
His posts are helpful?
5 1