Hello Everyone,
As we know that in almost all web applications there are certain things which need validations to be performed on
them. Validations can be performed in two ways that is client side and server side.
Client side validations are performed at the front end normally through java script and HTML's built in validations.
Server side validations are validations which are performed at the back end which are more secured and provides
utmost security when compared to client side validations.
So here are some useful server side validations provided to us by active records which we can use in our web apps
This validation validates the attributes by testing if they match the defined format of the regular expression which is
specified using the :with expression
class User < ActiveRecord::Base
validates :name, format: { with: /\A[a-zA-Z]+\z/,
message: "only allows letters" }
end
This validation validates the attributes by testing if the attribute values are included in the given set or not. If the
values wont match with the given set then we can display an error message like this
class Shirt < ActiveRecord::Base
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end
This validation validates the length of the attributes in many ways in which we can add different constraints as
follows
class Employee < ActiveRecord::Base
validates :name, length: { minimum: 20 }
validates :address, length: { maximum: 500 }
validates :password, length: { in: 8..20 }
validates :account_number, length: { is: 8 }
end
This validation validates the attributes by testing if the value is already present in the table or not. It wont let the
value to get saved into the table unless and until the value is unique and is already not present in the table.
class User < ActiveRecord::Base
validates :email, uniqueness: true
end
So these were some useful server side validations which we can use in our web apps.
0 Comment(s)