6

is there support for pattern attribute when using form_for?

<%= form_for order_form do |f| %>
<%= f.label "name" %>
<%= f.text_field :name, required: true %>
<%= f.label "Number" %>
<%= f.telephone_field :phone, pattern: "\\d{10}" %>
<%= f.submit %>

I'm trying to put together a regex pattern to ensure that phone numbers are in correct format. My problem is that the pattern attribute wont take regex only strings

<%= f.telephone_field :phone, pattern: /\d{10}/ %> doesnt work

so when i write the regex as a string it causes problems, (like having to escape backslashes e.g.

"\\d{10}" == /\d{10}/

should i just forgo using form_for on this form or is there a way to use form_for and pattern matching together

ChadTheDev
  • 399
  • 3
  • 13
  • 1
    You can use javascript for validation on forms on the front end, or rails model validations (and then also db validation) on the back end. Those are what I know of- it's possible form_for or html5 has validations of its own. – Dbz Dec 13 '16 at 00:00
  • 2
    Why is `pattern: "\\d{10}"` a problem? The [`pattern` attribute](https://www.w3.org/TR/html5/forms.html#the-pattern-attribute) in HTML holds text that is interpreted as a JavaScript regex (not a Ruby one). If typing `\\d` is really so much trouble then use `pattern: '\d{10}'` instead. Embedding one language inside another is always a little messy, more so when you're embedding one language (JavaScript regex) inside another (HTML) inside another (Ruby) inside another (ERB). – mu is too short Dec 13 '16 at 00:35
  • its not about escaping backslashes being a problem or a hassle, Im just trying to make sure i use best practices – ChadTheDev Dec 13 '16 at 03:07

1 Answers1

5

I was trying some similar but I work in Rails 5.1.4 My code is:

<%= form.telephone_field :telefono, id: :person_telefono,
:pattern => '\d{10}', :placeholder => "solo numeros"%>

Try to adapte it for your program and rails version.

Regards

kergrau
  • 61
  • 3
  • 8