Link to home
Start Free TrialLog in
Avatar of OVC-it-guy
OVC-it-guy

asked on

Need Regular Expression that allows letters, numbers, and standard puctuation

I am developing a web site in ASP.NET with VB.NET on MS Visual Web Developer.  I have a number of form fields requiring validation.  I have regualr expression, "^[a-zA-Z0-9]+(([\'\,\.\!\- ][a-zA-Z0-9 ])?[a-zA-Z0-9]*)*$", but I need one that allows numbers, letters, dash and standard punctuation (- . , ! ).  Can someone please help me with this?
Avatar of Muhammad Kashif
Muhammad Kashif
Flag of Pakistan image

What I understood that you want that your textbox should allow numbers, letters, dash and ... Not the regular expression with specific format.

Then you should use KeyDown and KeyPress event.

So use in following way It will allow only Numbers to be entered in TextBox1

In the same way you can add more checks.
e.g. for letters add check in KeyDown Event.

If e.KeyCode < Keys.A OrElse e.KeyCode > Keys.Z Then

Public EnteredText As Boolean
 
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    EnteredText = False
    If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
        If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
            If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Subtract Then
                EnteredText = True
            End If
        End If
    End If
End Sub
 
 
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If EnteredText = True Then
        e.Handled = True
        EnteredText = False
    End If
End Sub

Open in new window

Avatar of OVC-it-guy
OVC-it-guy

ASKER

That's a lot more code than what I'm looking for.  I just need the validationExpression similar to something like ^[-a-zA-Z0-9.,! ]$ might do it.  I was looking for some with more experince on this type of expression.
<asp:RegularExpressionValidator ID="CommentsRegex" runat="server" ControlToValidate="txtComments" ValidationExpression="^[a-zA-Z0-9]+(([\'\,\.\!\- ][a-zA-Z0-9 ])?[a-zA-Z0-9]*)*$" ErrorMessage="Please enter only letters, numbers and punctuation." />

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of petiex
petiex
Flag of United States of America 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
To make sure you are matching what you want to match, there's a nice regex tester here that I like to use: http://www.regular-expressions.info/javascriptexample.html

That site also has everything you could possibly want to know about regular expressions if you click around.
Thanks, petiex.