views:

27

answers:

2

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.

+1  A: 

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>
enobrev
+1  A: 

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

slainer68
+1 Thanks a lot Slainer!
sscirrus