Michael Randell
Michael Randell

Reputation: 45

Trying to use Regex to validate a field in a model. Works in Rubular but not in my validations

I'm trying to validate that input in a form field :item_type doesn't contain special characters or numbers.

Model:

class Item < ApplicationRecord
  has_many :order_items

  validates_format_of :item_type, :with => /[^A-Za-z\s]/
end

Controller:

def update
  @item = Item.find(params[:id])
  if @item.update_attributes(params_check)
    redirect_to items_path
  else #this is where I can use ActiveRecord errors object?
    redirect_to edit_item_path(@item)
    flash[:error] = "You must enter valid details"
  end
end

This regex only validates that the :item_type input contains a special character or integer. In Rubular, it matches the special character/integers.

If I remove '^' to make the regex /[A-Za-z\s]/, it allows all inputs through into the model. But, in Rubular, it selects all the regular string/space characters I'd like to let through.

This is basically my first time touching regex and I'm very confused at this point. I've spent hours try every which way I can think of. If anyone can help me, it would be greatly appreciated.

Upvotes: 2

Views: 207

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

In Rubular, that /[A-Za-z\s]/ just selects each letter or whitespace separately. In your code, you want to make sure the whole string meets the pattern, not just a separate char one by one.

Use

/\A[A-Za-z\s]*\z/ 

to match 0+ letters/whitespaces. Replace * with + to match 1 or more occurrences.

If you do not want to allow leading/trailing whitespace use

/\A[A-Za-z]+(?:\s+[A-Za-z]+)*\z/

(this won't allow an empty string) and if the space between letters can only be single, use

/\A[A-Za-z]+(?:\s[A-Za-z]+)*\z/

Upvotes: 1

Related Questions