Click here to Skip to main content
15,880,651 members
Articles / Programming Languages / XML
Article

Client and Server (Common) Validation Logic.

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL4 min read 4.7K   1  
Client and Server (Common) Validation Logic The Logic for validating input commonly on server side and showing the response onclient side is based on

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Client and Server (Common) Validation Logic


The Logic for validating input commonly on server side and showing the response on
client side is based on XMLHttpRequest (Clientside) and XMLDocument (Server Side).

In Steps:

1. First the form is converted to a well formed XML Request using function
PrepareForm(), this function returns the XML in string format.

 var PrepareForm = function(e, ID, RequestSender, ShowProgress, ExtraTags);

In the above function’s parameters:
e is the object of the container which is containing your form elements to be
submitted. This can be NULL
ID is the alternatively implemented id of the same container for which all
elements are to be posted to server. Alternatively this or e can be sent null.
RequestSender is the function delegate or object, which is utilized to sent the
resultant XML to server.


ShowProgress is the function delegate or object, which which is utilized to sent the
resultant XML to server.


ShowProgress is the function delegate or object, which is used to display loader
on screen while processing. This can be null.


ExtraTags is the ExtraTags to be added to request before sending to server.
E.g. it is required to send step information to server for processing multiple
inputs. Sample Extra tag string can be : “<STEP>1</STEP>”

The above function can be found in DGAjaxForm.js


2. Next, this XML string is sent to server side using ICallBackEventHandler, and on
server side this is grabbed by the ICallBackEventHandler Interface implemented
function called RaiseCallbackEvent.
Syntax:
public void RaiseCallbackEvent(String eventArgument)
{
XmlRequest.LoadXml(eventArgument);
}
In the above code XML String received from client is received by this function in
evetArgument variable. And in order to validate the XML Request it is loaded in to
XMLDocument Object using LoadXml method as shown above.


3. As the normal behavior of ICallBackEventHandler, after the above function
control is automatically sent to another ICallBackEventHandler Interface
Implemented function namely GetCallbackResult.
Syntax:
public string GetCallbackResult()
{
}

4. In the above function all the process of Request from client can be done.

a. Here we may validate the input first of all.
Example:

private Boolean Validate_Form(ref string Error)
{
ValidationHelper Validator = new ValidationHelper();
if (Validator.CheckRequired(ref XmlRequest, ref Error, "txtFirstName", "First
Name is Required!"))
Validator.CheckForCharacters(ref XmlRequest, ref Error, "txtFirstName",
"'&", "Single Quotes(') and Ampersand (&) are not allowed!");
if (Validator.CheckForCharacters(ref XmlRequest, ref Error,
"txtEmailAddress", "'&", "Single Quotes(') and Ampersand (&) are not allowed!"))
Validator.CheckAgainstExpression(ref XmlRequest, ref Error,
"txtEmailAddress", @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "Please enter a
valid Email ID!");
Error = Validator.ErrorXML;
return Validator.IsValid;
}
Above is a sample validation function for inputs being read from XMLRequest and
validated using ValidationHelper object (Code for the same can be found attached).
The updated GetCallbackResult function may look like:
public string GetCallbackResult()
{
string Error = "";
if (Validate_Form(ref Error))
{
// Perform your processing logic here
}
return Error;
}


5. Performing Custom implementation for Custom Tags in Response.
Example:
Suppose, as a requirement, the user is to be redirected to a specific page after
processing.
The Custom tag may be treated like this:
Error = Error.Replace("{Custom}", "<RedirectUrl><![CDATA[" +
Page.ResolveUrl("Thankyou.aspx") + "]]></RedirectUrl>");

 6. Handling Errors:
Example:
try
{
/// Perform error prone logics here
}
catch (Exception Ex)
{
Error = Error.Replace("SUCCESS", "FAILURE");
Error = Error.Replace("{DisplayMessage}", Ex.Message);
}


7. Performing Validation evolving DB interaction:
Suppose, the username is to be checked against database for availability.
if
(!CheckUsernameAvailibility(XmlRequest.GetElementsByTagName("txtEmailAddress")[0].ChildN
odes[0].Value))
{
Error = Error.Replace("SUCCESS", "FAILURE");
Error = Error.Replace("{DisplayMessage}", "User name '" +
XmlRequest.GetElementsByTagName("txtEmailAddress")[0].ChildNodes[0].Value + "' is
already taken, please enter another email address to continue!");
return Error;
}


8. Client Side Response Loading:
As implemented with ICallBackEventHandler, the client side response handling function
can be utilized for the same.
Example:
var HandleResponse = function(arg, context)
Here in the above function:
arg is the string containing the whole response XML return from Server as a response
of the processing done.
context is the context for which the current callback is treated [Depreciated here in
this implementation, and used no where.]
The above function is modified to have response converted into a object using the
following statement.

 var Response = new XML().LoadServerResponse(arg);


Here the variable “Response” is initialized with all tags as properties. Only Custom tag
remains untreated, which can be further distilled and processed accordingly.

9. Accessing and Processing Response:
a. Control wise Errors:
for (var i = 0; i < Response.length; i++) {
if (Response[i].ErrorMsg.toString() != " ") {
///the Control's Input is invalid
}
else {
/// the Control's Input is valid.
}
}

b. Checking for successful processing:

if (Response.isValid) {}

c. Displaying Server Messages (if any)

if (Response.DisplayMessage != "")

d. Processing Custom Tag
var UrlNode = Response.XMLDoc.getElementsByTagName("RedirectUrl");
Note: The above line is based on the example stated in point number 5 above
(“Performing Custom implementation for Custom Tags in Response”).

 

:: Project Files Can Be Downloaded From ::

http://LearningGeeks.Brinkster.Net/Validation/DGAjaxForm.js 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

755 members

Comments and Discussions

 
-- There are no messages in this forum --