Validations

This week I looked into validations as I was creating a rails app. The reasoning for using validations was to ensure that user accounts were created properly. I created an app in which a user must sign up or log in. So what happens when someone creates an account with a password such as “c” or “r”. These accounts can easily be hacked by anyone. Information will be compromised. How about if an account isn’t even created with an email? What if someone creates an account with this email: “abcccccc”. That clearly is not even an email, searching for this account through the database is not very convenient. Emails are very unique and can ensure that accounts are different.

This is where validations come in handy. What are validations? They are exactly what the name suggests. They validate a value before it used within your program. I would recommend using validations within your app only to ensure that your app works the way that it was designed to work. Luckily, Rails comes with many active record validations. This is how you go about adding validations to your app.

You will add the validations directly to your models. For example:

This is a file within the app that I created. This is the model called User.rb. This is where I will put in the validations. Notice the syntax of the validations. You must first type “validates” and follow it by the attribute of the model that needs the validation. In this case it is “:email”. Next you type in what validation you are looking for. In this example I used “presence:” which is set to “true”. This line of code ensures that any account made must have an email. This way a user doesn’t create an account with no email.

Some validations will require you to use ‘Regex’. Regex code used with validations comes in handy as it specifically requires what you are looking for. Here is another example pertaining to the app I created:

This image shows validations of email using regex on line 8.

This validation of email requires specific values or “rules” that I set using Regex. It requires a certain length of characters followed by ‘@’ followed by more characters. This way no one sets up an email as “abcccc”! Validations are great to use and can be flexible depending on what validation it is. Here is a source that will have plenty of Rails Validations… http://guides.rubyonrails.org/active_record_validations.html

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.