Search code examples
c#mysqlasp.netregexapostrophe

How to prevent ’ character being entered into a textbox?


I am trying to prevent the character from being entered into a textbox. The problem is if you copy and paste the character it becomes a right single quotation, which causes an error in the sql when trying to save the textbox to the database.

You can see this here in the unicode lookup

If you manually enter in ' then it is an apostrophe and this character is accepted.

The problem is people are copying and pasting this character from emails into the textbox and it gets converted to the single right quote.

Regex regex = new Regex(@"^[a-zA-Z0-9]*$");
Match match = regex.Match(txtName.Text);
if (!match.Success)
{
     DisplayMsg("Name contains invalid character");
}

Is there a way to still allow the user to enter an apostrophe but prevent the single right quotation?


Solution

  • Rather than preventing users from entering (especially if they are copying and pasting), you'd be better off replacing the character yourself if you really need to get rid of it:

    txtName.Text = txtName.Text
        .Replace((char) 0x2018, '\'')  // ‘ ‘
        .Replace((char) 0x2019, '\'')  // ’ ’
        .Replace((char) 0x201C, '"')   // “ “
        .Replace((char) 0x201D, '"');  // ” ”
    

    This way, you won't get in the way of your users and you'll still remove this character.

    However, it does sound like you might be building up queries using string concatenation, and this is a more serious problem!