murday1983
murday1983

Reputation: 4016

RegularExpressionValidator Not Working Correctly For Alphanumeric Field

I have an asp.net web app and I am trying to apply my RegularExpressionValidator to a field which should only allow alphanumeric characters and spaces but when ever I type (e.g. ss) in the field it fails my validator and either I'm having a brain fact or the issue is straight in front of me and I just cant see it.

HTML

<div class="form-group">
    <asp:Label ID="Label1" class="col-md-3 control-label" runat="server" Text="Enter full name" AssociatedControlID="txtData1"></asp:Label>
    <div class="col-md-3">
        <asp:TextBox ID="txtData1" runat="server" class="form-control"></asp:TextBox>
    </div>
    <div class="col-md-offset-3 col-md-9">
        <asp:RequiredFieldValidator Display="Dynamic" runat="server" ID="reqFullName" SetFocusOnError="true" ForeColor="Red" ControlToValidate="txtData1" ErrorMessage="Please enter your full name." />
        <asp:RegularExpressionValidator Display="Dynamic" runat="server" ID="regexpName"
                                        SetFocusOnError="true" ForeColor="Red"
                                        ControlToValidate="txtData1"
                                        ErrorMessage="Only alphanumeric characters are allowed."
                                        ValidationExpression="^a-zA-Z\s" />
    </div>
</div>

Upvotes: 0

Views: 247

Answers (1)

buckley
buckley

Reputation: 14089

This should do the trick

^[a-zA-Z\s]+$

This regex

  • validates that at least 1 alphanumeric character or whitespace is present (the "+")
  • also allows tabs or any other white space, ("\s")

The main problem with your regex is that you did not specify a quantifier ("+") and forgot to list the allow characters in a character class.

Upvotes: 1

Related Questions