Shilpi Agrawal
Shilpi Agrawal

Reputation: 615

Restrict users to enter special characters in rails

I want to use this regex /^[a-zA-Z0-9 ]*$/ for restricting special character in views itself

<%= text_field_tag :realname, params[:realname], :class => "form-control", placeholder: "Realname", id: "Text--AreaFocus" , pattern: "/^[a-zA-Z0-9 ]*$/" %>

I tried this above code but it doesn't seem working. Any help will be really helpful.

Upvotes: 2

Views: 2904

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You need to specify the class as "form-control" and remove the double quotes from around the regex that you declare using a literal:

<%= text_field_tag :realname, params[:realname], pattern: /\A[a-zA-Z0-9 ]*\z/, :class => "form-control", placeholder: "Realname", id: "Text--AreaFocus" %>
                                                         ^                   ^            ^^^^^^^^^^^^

Also, since it is RoR, to match the start and end of string, you should use \A and \z anchors instead of ^/$.

Upvotes: 1

Ashwin Yaprala
Ashwin Yaprala

Reputation: 2777

We can do pattern recognition with html tag.

<%= text_field_tag :realname, params[:realname], pattern: "/^[a-zA-Z0-9 ]*$/", :class => "form-control", placeholder: "Realname", id: "Text--AreaFocus" %>

Also I recommend you write validation in Model.

Upvotes: 0

Nikola Todorovic
Nikola Todorovic

Reputation: 310

Maybe this an help you?

So put something like this in your model:

validates_format_of :realname, :with: /^[a-zA-Z0-9 ]*$/

Upvotes: 0

Related Questions