Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put the Custom Validators in Rails 5?

Tags:

I am trying to add an email custom validators for my app; However, where should I place the custom validator? (I really do not want to place this validator class inside the model) Is there a cli generator for validator?

http://guides.rubyonrails.org/active_record_validations.html

class EmailValidator < ActiveModel::EachValidator   def validate_each(record, attribute, value)     unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i       record.errors[attribute] << (options[:message] || "is not an email")     end   end end  class Person < ApplicationRecord   validates :email, presence: true, email: true end 

What's the convention location/path for custom validator?

like image 841
X.Creates Avatar asked Feb 15 '17 15:02

X.Creates


People also ask

What methods should you implement for your custom validator?

Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.

What are custom validators?

A validator in Angular is a function which returns null if a control is valid or an error object if it's invalid. For model-driven forms we create custom validation functions and pass them into the FormControl constructor.

How do I create a custom validator?

Custom validators take the value from the FormControl , where every input acts as a FormControl . So let's create a form along with a validator function. Create a new file called customvalidator. validator.


1 Answers

I put them in /app/validators/email_validator.rb and the validator will be loaded automatically.

Also, I don't know if it's your case but you should replace this in your form. If so, a first validation is made before the user reach your controller.

  <div class="field">     <%= f.label :email %>     <%= f.text_field :email, required: true %>   </div> 

By :

  <div class="field">     <%= f.label :email %>     <%= f.email_field :email, required: true %>   </div> 
like image 149
devoh Avatar answered Sep 29 '22 10:09

devoh