Friday, June 18, 2010

Credit Card CVV Code Validation in ASP.NET



What is CVV?

The Card Verification Value (CVV) is an extra code printed on your debit or credit card. It sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or VCode), or Card Code Verification (CCV). CVV is a new authentication procedure established by credit card companies to further efforts towards reducing fraud for internet transactions. It consists of requiring a card holder to enter the CVV number in at transaction time to verify that the card is on hand.

CVV Code in Credit Cards

CVV for Visa, MasterCard, BankCard and Diners is the final three digits of the number printed on the signature strip on the back of your card. CVV for American Express appears as a separate 4-digit code printed on the front of your card.

CVV Code Validation

We will see how to validate a CVV number using JavaScript as well as C# in this article. I have written methods/functions in C# and JavasScript respectively for this validation. The JavaScript function validateCvvCode() is used to validate a CVV code at client side. The ValidateCVVCode() written in C# is used to check the CVV code at server side. These functions determines number of digits required for the given card type and then checks if the CVV Code have the required count of digits and have only numeric digits 0 to 9 using a regular expression. The regular expression is formed dynamically based on the card type.

Validation Using JavaScript


The following code contains the javascript function to validation CVV code with
HTML markup of the demo application.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CVVValidationDemo.aspx.cs"
Inherits="CVVValidationDemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CVV Credit Card Number Validation </title>
<script type="text/javascript" language="javascript">

function validateCvvCode() {

//Get the text of the selected card type
var cardType = document.getElementById('ddlCardType')
.options[document.getElementById('ddlCardType').selectedIndex].text;
// Get the value of the CVV code
var cvvCode = document.getElementById('txtCVVCode').value;

var digits = 0;
switch (cardType.toUpperCase()) {
case 'MASTERCARD':
case 'EUROCARD':
case 'EUROCARD/MASTERCARD':
case 'VISA':
case 'DISCOVER':
digits = 3;
break;
case 'AMEX':
case 'AMERICANEXPRESS':
case 'AMERICAN EXPRESS':
digits = 4;
break;
default:
return false;
}

var regExp = new RegExp('[0-9]{' + digits + '}');
return (cvvCode.length == digits && regExp.test(cvvCode))
}

function checkCvvCode() {

var result = validateCvvCode();
if (result)
alert('Valid CVV Code');
else
alert('Invalid CVV Code');
}

</script>

<style type="text/css">
.style1
{
font-size: large;
font-weight: bold;
font-family: Arial;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width="200px">
</td>
<td class="style1">
CVV Code Validation
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>
<asp:ValidationSummary ID="vsCVVValidationSummary" runat="server" />
</td>
</tr>
<tr>
<td width="200px">
Card Type
</td>
<td>
<asp:DropDownList ID="ddlCardType" runat="server" Width="250px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>

</td>
</tr>
<tr>
<td width="200px">
CVV Code
</td>
<td>
<asp:TextBox ID="txtCVVCode" runat="server"></asp:TextBox>
<asp:CustomValidator ID="custValidCVV" runat="server"
ErrorMessage="Invalid CVV Code">*</asp:CustomValidator>
</td>
</tr>
<tr>
<td width="200px">

</td>
<td>

</td>
</tr>
<tr>
<td width="200px">

</td>
<td>
<asp:Button ID="btnCvvServerValidate" runat="server" Text="Server Side Validation"
OnClick="btnCvvServerValidate_Click" />

<input id="hbtnCvvClientValidate" type="button" value="Client Side Validation"
onclick="checkCvvCode()" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>


Validation Using C#


The following code snippet has server side written in C# to demonstrate the CVV
code validation. I have loaded and checked the following card types in a dropdown
list for demonstration purpose: MASTERCARD, EUROCARD, EUROCARD/MASTERCARD, VISA,
DISCOVER and AMERICAN EXPRESS.

using System;
using System.Data;
using System.Text.RegularExpressions;

public partial class CVVValidationDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindCardType();
}

private void BindCardType()
{
System.Data.DataTable dtCardType = new System.Data.DataTable();
dtCardType.Columns.Add(new DataColumn("Card_Type_Id", typeof(int)));
dtCardType.Columns.Add(new DataColumn("Card_Type_Name", typeof(string)));

dtCardType.Rows.Add(new object[] { 1, "MASTERCARD" });
dtCardType.Rows.Add(new object[] { 2, "EUROCARD" });
dtCardType.Rows.Add(new object[] { 3, "EUROCARD/MASTERCARD" });
dtCardType.Rows.Add(new object[] { 4, "VISA" });
dtCardType.Rows.Add(new object[] { 5, "DISCOVER" });
dtCardType.Rows.Add(new object[] { 6, "AMEX" });
dtCardType.Rows.Add(new object[] { 7, "AMERICANEXPRESS" });
dtCardType.Rows.Add(new object[] { 8, "AMERICAN EXPRESS" });

ddlCardType.DataSource = dtCardType;
ddlCardType.DataValueField = "Card_Type_Id";
ddlCardType.DataTextField = "Card_Type_Name";
ddlCardType.DataBind();

}
protected void btnCvvServerValidate_Click(object sender, EventArgs e)
{
custValidCVV.ErrorMessage = "Invalid CVV Code";
custValidCVV.IsValid = ValidateCVVCode();
}

private bool ValidateCVVCode()
{
var cardType = ddlCardType.SelectedItem.Text;
var cvvCode = txtCVVCode.Text;

var digits = 0;
switch (cardType.ToUpper())
{
case "MASTERCARD":
case "EUROCARD":
case "EUROCARD/MASTERCARD":
case "VISA":
case "DISCOVER":
digits = 3;
break;
case "AMEX":
case "AMERICANEXPRESS":
case "AMERICAN EXPRESS":
digits = 4;
break;
default:
return false;
}

Regex regEx = new Regex("[0-9]{" + digits + "}");
return (cvvCode.Length == digits && regEx.Match(cvvCode).Success);
}
}



Verifying Credit Card Numbers Using Regular Expressions



With a few simple regular expressions, you can easily verify whether your customer entered a valid credit card number on your order form. You can even determine the type of credit card being used. Each card issuer has its own range of card numbers,identified by the first 4 digits.

You can use a slightly different regular expression to find credit card numbers,or number sequences that might be credit card numbers, within larger documents. This can be very useful to prove in a security audit that you're not improperly exposing your clients' financial details.

Validating credit card numbers is the ideal job for regular expressions. They're just a sequence of 13 to 16 digits, with a few specific digits at the start that identify the card issuer. You can use the specific regular expressions below to alert customers when they try to use a kind of card you don't accept, or to route orders using different cards to different processors.


  • Visa:^4[0-9]{12}(?:[0-9]{3})?$ All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
  • MasterCard:^5[1-5][0-9]{14}$ All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
  • American Express:^3[47][0-9]{13}$ American Express card numbers start with 34 or 37 and have 15 digits.
  • Diners Club:^3(?:0[0-5]|[68][0-9])[0-9]{11}$ Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
  • Discover:^6(?:011|5[0-9]{2})[0-9]{12}$ Discover card numbers begin with 6011 or 65. All have 16 digits.
  • JCB:^(?:2131|1800|35\d{3})\d{11}$ JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.

If you just want to check whether the card number looks valid, without determining the brand, you can combine the above six regexes into ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$ You'll see I've simply alternated all the regexes, and used a non-capturing group to put the anchors outside the alternation. You can easily delete the card types you don't accept from the list.

These regular expressions will easily catch numbers that are invalid because the customer entered too many or too few digits. They won't catch numbers with incorrect digits. For that, you need to follow the Luhn algorithm, which cannot be done with a regex. And of course, even if the number is mathematically valid, that doesn't mean a card with this number was issued or if there's money in the account. The benefit or the regular expression is that you can put it in a bit of JavaScript to instantly check for obvious errors, instead of making the customer wait 30 seconds for your credit card processor to fail the order. And if your card processor charges for failed transactions, you'll really want to implement both the regex and the Luhn validation.

Monday, June 14, 2010

JSON Inroducation


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.


JSON is built on two structures:



  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array,vector, list, or sequence.


These are universal data structures. Virtually all modern programming languages
support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.


In JSON, they take on these forms:


An object is an unordered set of name/value pairs. An object begins with
{ (left brace) and ends with } (right brace). Each name is followed by : (colon)and the name/value pairs are separated by , (comma).


What is jQuery And Why jQuery?

What is jQuery?
jQuery is great library for developing ajax based application. jQuery is great library for the JavaScript programmers, which simplifies the development of web 2.0 applications. You can use jQuery to develop cool web 2.0 applications. jQuery helps the programmers to keep code simple and concise. The jQuery library is designed to keep the things very simple and reusable.

jQuery library simplifies the process of traversal of HTML DOM tree. You can use jQuery to handle events, perform animation, and add the ajax support into your web applications with ease.

Why jQuery?
You can use simple JavaScript to perform all the functions that jQuery provides. Then why jQuery? The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

jQuery is java script and can be used with JSP, Servlets, ASP, PHP, CGI and almost all the web programming languages.

The jQuery code is very simple and easy to learn.

Here are the features of jQuery

  • DOM element selections functions
  • DOM traversal and modification
  • Events
  • CSS manipulation
  • Effects and animations
  • Ajax
  • Extensibility
  • Utilities - such as browser version and the each function.
  • JavaScript Plugins

Saturday, June 12, 2010

Free ASP.NET MVC Tutorial


The announcement made by Scoot Guthrie on 11-March-2009 that you can now download the tutorial for MVC.

The free ASP.NET MVC Tutorial having following points covered along with images.

  • File->New Project
  • Creating the Database
  • Building the Model
  • Controllers and Views
  • Create, Update, Delete Form Scenarios ViewData and ViewModel
  • Partials and Master Pages
  • Paging Support
  • Authentication and Authorization
  • AJAX Enabling RSVPs Accepts
  • Integrating an AJAX Map
  • Unit Testing

You can find the original post by ScootGu from here, and the PDF from here.

A sample application for ASP.NET MVC you can find it from Codeplex.



Friday, June 11, 2010

JSON Calling from MVC Page


HTML:

<%= Html.DropDownList("", new SelectList(ViewData["States"] as IEnumerable, "Id", "Name", Model))%>
<%= Html.DropDownList("", new SelectList(ViewData["Cities"] as IEnumerable, "Id", "Name", Model))%>


Javascript:

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("select[id='StateId']").change(function() {
$.ajax({
type: "POST",
url: "/Supplier/StateCityInfo/",
data: { StateId: $(this).val() },
dataType: "json",
error: function(xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
alert(status);
},
success: function(data) {
$("#CityId").empty();
$.each(data, function(key, City) {
$("#CityId").append($("<option></option>").val(City.Id).html(City.Name));
});
}
});
})
})
</script>


Supplier Controller:

public class SupplierController : Controller
{
[AcceptVerbs("POST")]
public ActionResult StateCityInfo(int StateId)
{
return Json(this.AllCity(StateId));
}
}


Saturday, June 5, 2010

Merge Statement

 

SQL Statement:

DECLARE @tblMergeOutput TABLE
(
ID BIGINT IDENTITY(1,1)
, MergeAction NVARCHAR(100)
, InsertedId INT
, DeletedId INT
, GroupID INT
)

CREATE TABLE #tblSource ( ID INT, GroupID INT, Name VARCHAR(10) )
CREATE TABLE #tblTarget ( ID INT, GroupID INT, Name VARCHAR(10) )

INSERT INTO #tblSource VALUES (1,1,'a11')
INSERT INTO #tblSource VALUES (2,1,'a21')
INSERT INTO #tblSource VALUES (3,1,'a31')
INSERT INTO #tblSource VALUES (4,1,'a41')

INSERT INTO #tblTarget VALUES (1,1,'a1')
INSERT INTO #tblTarget VALUES (3,1,'a3')
INSERT INTO #tblTarget VALUES (5,1,'a5')
INSERT INTO #tblTarget VALUES (6,2,'b2')
INSERT INTO #tblTarget VALUES (7,2,'b1')

MERGE #tblTarget
USING (
SELECT *
FROM #tblSource
) AS tblSource
ON tblSource.GroupID = #tblTarget.GroupID
AND tblSource.ID = #tblTarget.ID
WHEN MATCHED THEN
UPDATE
SET Name = tblSource.Name
WHEN NOT MATCHED THEN
INSERT (
ID
, GroupID
, Name
)
VALUES (
tblSource.ID
, tblSource.GroupID
, tblSource.Name
)
WHEN NOT MATCHED BY SOURCE AND #tblTarget.GroupID = 1
THEN DELETE
OUTPUT
$action
, inserted.Id
, deleted.Id
, tblSource.GroupID
INTO @tblMergeOutput;

SELECT * FROM #tblSource
SELECT * FROM #tblTarget order by GroupID, ID
SELECT * FROM @tblMergeOutput

DROP TABLE #tblSource
DROP TABLE #tblTarget
 
Target Table Output:
 ------------------
ID GroupID Name
------------------
1 1 a11
2 1 a21
3 1 a31
4 1 a41
6 2 b2
7 2 b1
------------------
 
Merge Table Output:
----------------------------------------------------
ID Merge Action InsertedID DeletedID GroupID
----------------------------------------------------
1 INSERT 2 NULL 1
2 INSERT 4 NULL 1
3 UPDATE 1 1 1
4 UPDATE 3 3 1
5 DELETE NULL 5 NULL
----------------------------------------------------