Link to home
Start Free TrialLog in
Avatar of RIAS
RIASFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Validate on a maskedtextbox

Hello,
I am validating a credit card with the  check can be described as follows.
For the number 49927389716
Reverse the digits:  61798372994
Sum the digits as odd positions:  6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
The even positioned digits:    1,  8,  3,  2,  9  Multiply each even positioned digit by 2:    2, 16,  6,  4, 18
  Sum the digits of each multiplication:    2,  7,  6,  4,  9  And them sum them:    2 + 7 + 6 + 4 + 9 = 28 = s2
Add  s1 and s2 and perform mod 10 s1 + s2 = 70
which ends in zero which means that 49927398716 passes the Luhn test




Private Function ValidateLuhn(ByVal value As String) As Boolean
02
	 
03
	    Dim CheckSum As Integer = 0
04
	    Dim DoubleFlag As Boolean = (value.Length Mod 2 = 0)
05
	 
06
	    Dim Digit As Char
07
	    Dim DigitValue As Integer
08
	    For Each Digit In value
09
	        DigitValue = Integer.Parse(Digit)
10
	        If DoubleFlag Then
11
	            DigitValue *= 2
12
	            If DigitValue > 9 Then
13
	                DigitValue -= 9
14
	            End If
15
	        End If
16
	        CheckSum += DigitValue
17
	        DoubleFlag = Not DoubleFlag
18
	    Next
19
	 
20
	    Return (CheckSum Mod 10 = 0)
21
	 
22
	End Function

Open in new window


Any suggestion on a good code here
Avatar of it_saige
it_saige
Flag of United States of America image

Try this on for size:
Public Class Form1
	Private Sub OnMaskInputRejected(sender As Object, e As MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected
		MessageBox.Show(String.Format("{0} was rejected; {1}", e.Position, e.RejectionHint))
	End Sub

	Private Sub OnTypeValidationCompleted(sender As Object, e As TypeValidationEventArgs) Handles MaskedTextBox1.TypeValidationCompleted
		If e.IsValidInput Then
			If e.ReturnValue.ToString().Length < 16 Then
				MessageBox.Show("The entered card number must contain 16 digits.")
				e.Cancel = True
			ElseIf Not e.ReturnValue.ToString().LuhnValidation() Then
				MessageBox.Show("Entered card number is invalid.  Failed Luhn.")
				e.Cancel = True
			End If
		Else
			MessageBox.Show("The entered card number must contain 16 digits.")
			e.Cancel = True
		End If
	End Sub
End Class

Module Extensions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function LuhnValidation(ByVal source As String) As Boolean
		Dim result As Boolean = False
		Try
			' We should validate that we are dealing with integers.
			If source.All(Function(c) Char.IsNumber(c)) Then
				' Rules of algorithm
				' 1.  Reverse the order of the digits in the number.
				' 2.  Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
				' 3.  Taking the second, fourth ... and every other even digit in the reversed digits:
				'     a.  Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
				'     b.  Sum the partial sums of the even digits to form s2
				' 4.  If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
				' Code from - http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Visual_Basic_.NET
				result = source.Select(Function(c, i) (AscW(c) - 48) << ((source.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0
			End If
		Catch ex As Exception
			result = False
		End Try
		Return result
	End Function
End Module

Open in new window

-saige-
Avatar of RIAS

ASKER

Hello Saige,
Thanks for the advise but I get tese errors:
Error      1      'LuhnValidation' is not a member of 'String'
Error      2      'All' is not a member of 'String'.  
Error      3      Expression expected.      
Error      4      'Select' is not a member of 'String'.      
Error      5      Expression expected
Error      6      Name 'i' is not declared.      
Error      7      Name 'c' is not declared.      
Error      8      Name 'i' is not declared.      
Error      9      End of statement expected.
Avatar of RIAS

ASKER

 Public Function LuhnValidation(ByVal source As String) As Boolean
        Dim result As Boolean = False
        Try
            ' We should validate that we are dealing with integers.
			If source.All(Function(c) Char.IsNumber(c)) Then
                ' Rules of algorithm
                ' 1.  Reverse the order of the digits in the number.
                ' 2.  Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
                ' 3.  Taking the second, fourth ... and every other even digit in the reversed digits:
                '     a.  Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
                '     b.  Sum the partial sums of the even digits to form s2
                ' 4.  If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
                ' Code from - http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Visual_Basic_.NET
				result = source.Select(Function(c, i) (AscW(c) - 48) << ((source.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0
            End If
        Catch ex As Exception
            result = False
        End Try
        Return result
    End Function

Open in new window

The implementation I presented is as an extension method (hence it's inclusion in a Module and the Extension() attribute).

What .NET version are you using?  If 3.5 or above, try adding an Import for System.Linq to the top of your form code.

-saige-
Avatar of RIAS

ASKER

Hello,

I am using vb.net 2005 ..tried adding  System.Linq but same error

Cheers
I mean what .NET version (not Visual Studio version).

1. Right click on your project and choose properties -[b]or[/b]- Choose '[b]Project[/b]' -> '[b]<project name> Properties[/b]' from the menu.

User generated image

2. Select the '[b]Compile[/b]' tab.

User generated image

3. Press (or click) the '[b]Advanced Compile Options...[/b]' button.

User generated image

4. Look at the selected '[b]Target framework (all configurations):[/b]' drop down.

User generated image-saige-
Avatar of RIAS

ASKER

Hello Saige,
Does not have the information there.Please find the attached copy.

Compiler.docx
ASKER CERTIFIED SOLUTION
Avatar of Athar Syed
Athar Syed
Flag of Kuwait image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RIAS

ASKER

Worked mate!!!!
Just posting this version for brevity's sake:
Private Function LuhnValidation(ByVal source As String) As Boolean
	Dim result As Boolean = False
	Try
		' We should validate that we are dealing with integers.
		If Not IsNumeric(source) Then Exit Function

		' Rules of algorithm
		' 1.  Reverse the order of the digits in the number.
		' 2.  Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1
		' 3.  Taking the second, fourth ... and every other even digit in the reversed digits:
		'     a.  Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
		'     b.  Sum the partial sums of the even digits to form s2
		' 4.  If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.
		Dim sum As Integer = 0
		For i As Integer = source.Length - 1 To 0 Step -1
			If i Mod 2 <> 0 Then
				sum = sum + (AscW(source(i)) - 48)
			Else
				If ((AscW(source(i)) - 48) * 2) > 9 Then
					sum = sum + ((((AscW(source(i)) - 48) * 2) \ 10) + (((AscW(source(i)) - 48) * 2) - 10))
				Else
					sum = sum + ((AscW(source(i)) - 48) * 2)
				End If
			End If
		Next
		result = sum Mod 10 = 0
	Catch ex As Exception
		result = False
	End Try
	Return result
End Function

Open in new window

-saige-
Avatar of RIAS

ASKER

Thanks Saige you are of great help!!Cheers mate!