3

How can i restrict '♥♣' like characters from saving into database. If these characters appear in name text field, a error message should be thrown. I am using ruby on rails.

Thanks, Anubhaw

Anubhaw
  • 5,978
  • 1
  • 29
  • 38
  • Do you want to prevent certain characters (blacklist), or prevent everything but a certain set of characters (whitelist)? – aularon Sep 08 '10 at 10:09
  • Whitelisting is better (if possible) since then you're not going to get surprised by things you didn't think about. (Well, you're less likely to be surprised by them…) – Donal Fellows Sep 08 '10 at 10:10
  • Actually i want restrict name like '♥♣name♣♥' this. Value for following ♣♥ in database is ♥♣. So how do i restrict following and look alike. – Anubhaw Sep 08 '10 at 10:19
  • 1
    Why do you want to do this? Man, I hate when I can't write my lastname (with an ä) into a textbox for some godforsaken reason. Protect yourself from SQL injection using parameterized queries instead. – erikkallen Sep 08 '10 at 10:26
  • 3
    It looks like your issue is actually a different one: Your database is misconfigured: Use UTF-8; Everywhere; Always. – Williham Totland Sep 08 '10 at 10:30
  • 1
    @Williham: No, sometimes you want UTF-16 :) – erikkallen Sep 08 '10 at 12:24
  • @Williham - UTF-8 takes up MORE space than UTF-16 when the majority of your characters are outside the traditional ASCII set. So yes, sometimes, for some languages, you want UTF-16. – Joel Mueller Sep 08 '10 at 18:17

2 Answers2

6

See this for an example of allowing only a specific set of characters (whitelisting), which IMO is better and safer:

var allowed = /[a-ZA-Z0-9]/; // etc.

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // Cross-browser
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is the key allowed?
        if (!allowed.test(char)) {
            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

From: prevent typing non ascii characters in a textbox

Alternately you can use regex to strip out non ascii characters.

see here: How to remove all non - ASCII characters from a string in Ruby

Community
  • 1
  • 1
Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
  • 2
    +1 for good javascript solution. However a check in RoR before inserting into the database will also be required. – Thomas Sep 08 '10 at 10:18
1

You want some javascript to tell users when they put such characters in the form. You need a validation routine in your RoR code to make sure that only acceptable characters are actually placed in the database.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215