Search code examples
sqlregexapostrophe

Regular expression of ' and "


what is the regular expression to not allow enter ' and '' ?

because when the user enter the text with ' Example : i'm Mr Right -> it cause a error on SQL 2008.

i know, that i have 2 choice:

  1. not allow user to enter ' and "" (with regex)
  2. i will replace all the ' with \' and " with \" (i don't know if it work)

solution with regex:

<dx:ASPxTextBox runat="server" EnableClientSideAPI="True" Width="160px" ID="Info"
                            ClientInstanceName="Email">
                            <ValidationSettings SetFocusOnError="True">
                                <RegularExpression ErrorText="Invalid e-mail" ValidationExpression="" />
                                <RequiredField IsRequired="True" ErrorText="E-mail is required" />
                            </ValidationSettings>
                        </dx:ASPxTextBox>

solution with replace:

Info.Replace("'", "\'");

Thanks you in advance, Stev


Solution

  • The regex is ^[^'"]*$ which will accept anything but those two characters.

    To write this in C# use:

    @"^[^'""]*$"
    

    If you plan to insert the address into the DB you will probably need to remove or escape additional characters. Actually you should use something that does this automatically such as linq-to-sql or entity-framework.