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?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With