Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • validations in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 245
    Comment on it

    Validation

    There must be something twirling inside your mind after seeing validations in ruby, validation

    are basically used to check whether you are sending right parameters or not. i will explain you

    by brief code

    class School < ActiveRecord::Base
      validates :name, presence: true
    end
     
    School.create(name: "Delhi").valid? # => true
    School.create(name: nil).valid? # => false

    As you go through above code you have seen that in a class School we validates name, School will not validate it without name attribute, it is necessary to pass name attribute in School class, it will not permit second School as it has give nil as name attribute.

     

    Use of Validation

    we use validation to permit exactly what attribute we want to send in database,As you have seen in many websites login page we cannot enter name attribute in email  textbox, only valid email address will be send to database otherwise it would be cumbersome for end user.

     

    To Check Whether Validation is valid or not

    if you want to check whether your validation object is valid or not we well do like this

    class School < ActiveRecord::Base
      validates :name, presence: true
    end
     
    School.create(name: "Delhi").valid? # => true
    School.create(name: nil).valid? # => false

     

    valid? will check whether the given attribute is valid or not

     

    Here are list of validation we can used in input text

    1.Validates length of passed string

    We can also check whether the length of passed string is more than what we have validated.

    class School < Active Record: :Base
    validates length_of :name, maximum=>30


     

    validates_acceptance_of

    This will accept only 'Y' value for new field.

     validates_acceptance_of :new            
                            :accept => 'Y' 
    

    validates_confirmation_of this will confirm whether password field is matching with password_confirmation

     validates_confirmation_of :password 
    


     

    validates_numericality_of This  ensures the numericality of field

     
    
        validates_numericality_of :value
    
         :only_integer=> true
    
         :allow=> nil
    
    

     

 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: