Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Format Validators in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 484
    Comment on it

    Hi Friends,
    Hope you are doing well with your work. Today I am here with one of the most common topics in Rails that is format validators in rails. Lets start with defining validation.
    "Validations are used to avoid the invalid data to get stored into the database"
    There are so many ways to validate the data before getting saved. One can use client side validation, native database level constraints or controller level.
    Rails provides built-in helpers for the common use cases that are used in mostly every site. That can be used inside a class directly. I have already covered three of these helpers in my previous blogs Virtual Attributes in rails and Validating Associate models in Rails.
    Today I am going to cover format validator.
    The format validator validates whether an attribute matches a given regular expression or not. It uses two options for that:

    (a) with: If we want attribute value to match given regular expression
    (b) without: If we want attribute value to not match given regular expression

    Example: Suppose we want to validate email of user then the class would be like:

    class User < ActiveRecord::Base
      validates :email, format: { with: /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i,
        message: "Allows only proper email format" }
    end
    


    Hope you liked it for more kinds of validation you can check here

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: