Click here to Skip to main content
15,896,453 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to disallow space in between and special characters server side in asp.net with c#. For instance if the text is jebin user/jebin.user/jebin@user etc it must validate else if it is jebin and simply space it must go fine.

What I have tried:

js validation is used which is not working.
Posted
Updated 10-Feb-17 5:25am
Comments
[no name] 10-Feb-17 9:34am    
"js validation is used which is not working.", if that is the C# code that you have tried, I can see why you are having trouble.
Karthik_Mahalingam 10-Feb-17 9:45am    
not clear.
Provide more info.
use Improve question to update the question.
F-ES Sitecore 10-Feb-17 9:46am    
We don't know how you are validating your data so can't possibly help you. This is why it is important to post the relevant code.

First, trim your string:
C#
string input = myTextBox.Text.Trim();
Then just use Linq methods:
if (input.Any(c => !char.IsLetterOrDigit(c)))
    {
    // Contains special character
    ...
    }
But me? I'd do it in javascript as they typed rather than as a "final validation" on the server.
 
Share this answer
 
Or, you can employ the RequiredFieldValidator and RegularExpressionValidator

Assuming this is ASP.NET webform and the valid letter are a-z,A-Z and 0-9, then on the UI

ASP.NET
<asp:TextBox ID="TextBox2" runat="server" CausesValidation="True"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ErrorMessage="*" ControlToValidate="TextBox2"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2" Display="Dynamic" 
            ErrorMessage="letter and number only" ValidationExpression="^[a-zA-Z0-9]+$"></asp:RegularExpressionValidator></div>

and in the code behind/server side

C#
if (Page.IsValid)
        {
            //pass validation, do server side processing. To test this part, disable the JavaScript on the browser
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900