Ruby on Rails Validations
In continuation of previous article, where we created a basic rails application, let continue to add validations to the fields. Validations are necessary to insert the data in your application as per your expectation.
There are many validations that are available in ruby on rails. To name some of them are as follows:
Here we will be implementing the presence validation to make sure we do not enter blank value.
In previous article we have created an application named book store, where we were inserting the books and some of its details like name, author's name, genre and publication name. We can implement validation on name of the book and author's name.
In app/models/book.rb make following changes to define validations
After adding above validations when you run the server and try to add the book details without entering the name of the book or author's name, you will prompted with errors saying the blank values are not allowed as shown below
Here you can see that validation defined in the model is restricting you to enter invalid data. To successfully enter the data in you application, now you need to enter at least book's name and its author's name.
Recommended by LinkedIn
Customize error message
Now when you try to enter the record for book without its name, you will see following:
Here you can see that the default error message is changed with the custom error message that we have written in model. Also here you can see that the value of author's name is entered and when we tried to submit the form, the error of the blank author name was removed.
This is an example of basic validation in rails application. You can try to implement this validations in your application. Later we will see implementation of different types of validations of rails.
In next article you will be able to implement authentication.
Till then cheers!!!
Nice example