sscirrus
sscirrus

Reputation: 56749

Restrict characters entered into a text_field

I have a text field where users enter a URL string, which cannot contain spaces or non-alphanumeric characters (if that's an accurate way of putting it).

Is there a way in Rails to restrict entry into the text_field itself so that spaces and characters like /":}{#$^@ can be avoided?

Thanks a lot.


To clarify, the only characters that should be possible are letters and numbers.

Upvotes: 3

Views: 1743

Answers (2)

Nicolas Blanco
Nicolas Blanco

Reputation: 11299

You may use jQuery Tools Validator that uses HTML 5 tags to validate your forms. This is a great way to validate your forms in an Unobscursive way without putting JS all over your forms :-).

Look at the "pattern" HTML 5 tag that allows you to validate a field against a Regexp.

http://flowplayer.org/tools/validator/index.html

Upvotes: 1

enobrev
enobrev

Reputation: 22542

The problem here is that URL strings can have slashes (/) and hash marks (#). So your regex is going to be quite complex to ensure the right portion of the field is filtered properly. But for plain character filtering, you can use simple regex to remove any non alpha-numeric characters.

Not sure about anything ruby-specific, but in straight javascript:

<html>
    <body>
        <form>
            <input type="text" name="whatever" id="form-field" value="" />
        </form>
    </body>
    <script type="text/javascript">
        var oFormField = document.getElementById('form-field');
        oFormField.onkeyup = function() {
            oFormField.value = oFormField.value.replace(/[^a-zA-Z0-9]/, '');
        }
    </script>
</html>

Upvotes: 2

Related Questions