Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Lessons:14Length:2.4 hours
  • Overview
  • Transcript

2.3 Validation

Validation of user input is crucial for maintaining the integrity of our data. In this lesson, you’ll learn about the many different validation helpers that come bundled with the Rails framework and how you can use them in your models.

Related Links

2.3 Validation

Now that we have a solid mechanism for managing projects and their tasks, we can focus our attention on the details now. I'm going to start off with one thing that usually is very hard to accomplish. It takes a lot of work but the way that Rails does it makes it really, really simple. For example, I'm inside the projects list, and I want to create a new project. What if I accidentally type no name whatsoever? So the project comes out empty. I do remember to change the end date. For example, I changed this to whatever date I want. But I forget to type in the name. If I create a project right away the project is successfully created but it doesn't have any name to it. This is something that is really obnoxious sometimes. We want to prevent the user from submitting faulty data or no data at all. And because of that we need to implement a validation mechanism. With validations, this is really simple. Validations are part of the integrity of the business entity, the model. So, what better place to go to that specific model. Let's go to app > models, and then project. And we type in a directive to the project class. Validates and then the actual rule that we want to implement. The way we do that is by typing validates presence of and then the attribute. In this case it is just the name. By typing this specific instruction, we will prevent new projects from being created with an empty name. Because of this, we won't have that issue when creating a new project with no name. The same goes for editing one project. So it works both ways. Both by creating a new project and when editing an existing project. So if I choose to update the project right away, you will see an error message. This is pretty cool, with a single directive we're able to create a protection mechanism. So you will see the list of errors in that model, so when trying to save the project, it will validate all of the conditions necessary for the project to be created. And if it does have some errors, it is going to print them out in the page. Also, it is going to highlight the respective field. So you can see that the name here is invalid. So from here, I can type in the appropriate name, so, My Second Project And when pressing enter, the project is successfully updated. Remember, for both creating and updating the projects, the rules are in place. Now, this is just one validation rule, but there are many others. There's this particular website from the official guides on Ruby on Rails. In this specific document, you have all of the information regarding validations. So if there's any validation that you might want to look up, go ahead and check this document. I'm going to skip directly to the validation helpers. These are the methods that you can use the same way as we did, In our very own project. You will see a difference between using validate's presence of and validate's name and then presence true. This previous instruction I typed is an old habit of mine. This was the old way of declaring specific validations. But now the Rails' four way is actually by typing the attribute first and then the rule. As you will see in the helpers, you see many different ones that have this way of declaring the rules. So you define validate, for example, terms of service, and then acceptance true. This acceptance method basically mandates the user to actually check a check box. Actually, this example of accepting the terms of service is a great example. You demand the user to check that check box in order for him to be aware of certain conditions or something. The next method 2.2, is validates_associated. Basically, you want to validate a nested associated records, we are going to do with this later in the course because this has to do with nested resource creation. Consider the example where you're creating a project with a bunch of tasks already defined. If you wish to do it and you want to validate the tasks. For example, the title for that task should not be empty. You would type in something like, validates associated, and validation would occur with those nested resources. Next we have the conformation helper, which is pretty useful when you want to confirm a piece of data. The example you see here, is the email confirmation. Sometimes when we want to confirm an email, for example, for placing an order, or for double-checking the address for the user, this is a good way of doing it. Notice how you need the underscore confirmation suffix appended to another text field. So, email, and then email_confirmation. This is the mechanism that builds supports to support this validation. It is also a good idea for example to double check the password to make sure the user has typed it correctly. So this has some pretty good use cases. Basically it's just for the user making sure that he has typed some input correctly. I'm going to skip a couple of helpers, because they are not used that often. I want to focus on the main ones. For example, the length validation allows us to assert that a particular input has a specific length rule. You can see that the examples are pretty straightforward. In the name, for example, we want to make sure that we have at least two different characters. So typing a name like just a J or an M wouldn't do. A minimum of two is required. We can also specify a maximum length, so an input should not be longer than 500 characters. The length of a particular item for example the password, should be something in between the values of our range. And also we can specify a mandatory length. So neither more or less, it should be the exact length. So either a minimum, a maximum, a range or a specific value. This is probably very useful for serial numbers or something like that. They need to have a specific format and the most flexible and permissive way of validating such a serial number is by typing a length validation. The numericality validator is actually pretty funny, I like it a lot. Basically, it mandates the user to type in a number, either a number or a float. Because, as you can see here, this games_played validation, demands an integer, only. This is an option that you can type in. Which forces only whole numbers to be typed in. And not floating point numbers. However, if you don't specify this option, then any number will do. You also have many different options as you can see from this list of possibilities. Clearly, you have multiple rules, for example specifying that the number must be even or odd, less or greater than a particular value, or a specific value too. So equal to and then that value. So many options for this numerically validation are available. We've already checked the presence validator. Basically you want to check that that particular attribute is present. And that's it. The absence validator is actually pretty much the opposite. You validate that the input is actually not there, instead of present which demands that it is there. So absence true will make it so that it should be nil or empty. The uniqueness validator is actually pretty cool. Take the email validator for example. You don't want to have more than one user with the same email. And so you apply a uniqueness validation that actually fetches all of the emails that match that email you typed, and if there's already one email address in there then it gets rejected. The last validation helper that you see here validates with. This is a generic validator that basically allows you to inject your own validation rules. So when you type a validates_with and a class, it basically implies that you have a class like this. It adheres from active model validator, and then you inject the validate, you define it, and do the basic validation. The way you handle validation is by resorting to the record's errors. You tell whether a record is valid or not by the errors that are present in the record. So if you add one error it is no longer valid. And that's it. Pretty straight forward. Most likely you will have a custom validation that we will like to have. But Rails does it really implement it at all? So you do that. Now you have loads of different options in this document, little customizations that you can type into your validations that make it a little more flexible and suitable for whatever it is we need to implement. I'm going to give you these two examples and then you can search for the remaining ones in the document. There's a link in the description below you can check out. So the allow_nil option basically allows us to override the validation if we simply don't have that attribute in the list of parameters being set. Basically you create an object with a hash of parameters. If a specific attribute is not in the hash of attributes, than we can just override the validation and let it go. The allow blank is a little different. Basically it allows us to type in an empty string in case we have something like a length option. This is a pretty good example. The allow blank wouldn't really be suitable for a presence validator because that one actually assumes that we don't want to allow the blank string. It is much more suitable for different validations for example the length validator is pretty cool. We demand that the title is five characters long, but if there isn't anything to paste so we get an empty string from the hash of parameters, then we just let it go, we skip the validation all together. So these are the most basic validation pools that we can use in Ruby on Rails. We're going to take advantage of them in the following lessons of the course. We're going to add more value to the application with these validations in the upcoming lessons. So stay tuned.

Back to the top