Search code examples
c#asp.netregexspecial-characters

Disallow if user eneter All special characters in textbox validation c#


I am working on validation, i have to validate a textbox, in which i need to disallow the special characters to enter. i mean if user fill only special characters in the textbox then we need to disallow him, if he is using test-test or test_test or (999)-998-1111 then we need to allow user to enter the data.

i have used the below regular expression, but this is disallowing all, even i enter a single Special Character. it shows me error.

<asp:RegularExpressionValidator ID="ReqValContactPerson_SpecialChars" runat="server" CssClass="changecolor" 
                    ControlToValidate="txtFirstName" Display="Dynamic" 
                    ErrorMessage="Please enter valid first name" SetFocusOnError="True" 
                    ValidationExpression="[\%\/\\\&\?\,\'\;\:\!\-]+" 
                    ></asp:RegularExpressionValidator>

Please help me.


Solution

  • The below regex won't allow only the mentioned special characters to be present on that textbox.

    ValidationExpression="^(?![\%\/\\\&\?\,\'\;\:\!\-]+$).+" 
    

    OR

    To disallow only digits and / or non-word characters.

     ValidationExpression="^(?![\d\W]+$).+" 
    

    \W matches any non-word character. \d+ matches one or more digits.

    That is, this won't allow %&' but allows this f%G'. Change .+ to .* only if you want to allow blank lines also.