Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex pattern with form for ruby on rails

Tags:

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

like image 839
ChadTheDev Avatar asked Dec 12 '16 23:12

ChadTheDev


People also ask

What does =~ mean in ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What kind of regex does ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

How do you match a string in ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.


1 Answers

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

like image 187
kergrau Avatar answered Sep 22 '22 16:09

kergrau