开发者

Restrict characters entered into a text_field

I have a text field where users enter a URL string, which cannot co开发者_运维百科ntain 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.


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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜