1
\$\begingroup\$

Is this a better way to validate a text box for mobile number only?

Validation:

  • allow only numbers
  • will not allow to paste string including characters
  • allow copy from the box
  • length is set to 10 without country code
  • allow back space

Suggest some methods to help me improve my function.

Public Sub mob_validation(ByVal e As System.Windows.Forms.KeyPressEventArgs, ByVal mob As TextBox)
        If e.KeyChar = Chr(22) Then
            Dim output As String = New String((From c As Char In Clipboard.GetText.ToString Select c Where Char.IsLetter(c)).ToArray())
            If output = "" And Len(mob.Text) = 10 Then
                mob.ForeColor = Color.Green
            Else
                mob.ForeColor = Color.Red
                Clipboard.Clear()
            End If
        Else
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                If Asc(e.KeyChar) <> 8 Then
                    If Asc(e.KeyChar) <> 3 Then
                        e.Handled = True
                        mob.ForeColor = Color.Red
                    End If
                End If
            Else
                mob.ForeColor = Color.Green
            End If
        End If
    End Sub
\$\endgroup\$
  • 3
    \$\begingroup\$ Please indent your code as I already told you in another review. It's even unreadable for a review! \$\endgroup\$ – ComFreek Aug 3 '14 at 15:54
  • \$\begingroup\$ use regex that will better \$\endgroup\$ – paritosh Aug 3 '14 at 16:04
  • \$\begingroup\$ @paritosh - your suggested edit would make a better answer... code indentation is a reviewable aspect of the question \$\endgroup\$ – rolfl Aug 3 '14 at 16:20
  • \$\begingroup\$ With all good intentions: I've been seeing this user over at SO all day posting/answering a lot of questions. And believe you me, if you ever see any hints of indenting, it's by accident. IMO, for the good of the community (SE), he should be taught to indent the code. \$\endgroup\$ – Bjørn-Roger Kringsjå Aug 3 '14 at 16:49
  • 2
    \$\begingroup\$ Great! Downvote revoked. Keep in mind that good formatted questions/answers tends to gain more votes;) \$\endgroup\$ – Bjørn-Roger Kringsjå Aug 3 '14 at 16:59
5
\$\begingroup\$

Again, properly indent the code. The code was unreadable to the point that we broke our own rules and edited the code in question just to be able to review it.

Other than that, the biggest issue with this is all of the magic numbers. They mean absolutely nothing to Mr. Maintainer. Normally at this point, I tell people to create an Enum, but in this case, there's one built in. Use the Keys Enumeration to replace all of those hardcoded numbers.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.