Using JavaScript to Display ActiveRecord Validation Errors

Daniel Mekuriaw
Geek Culture
Published in
5 min readAug 10, 2021

--

This blog explores the several server-side validation methods ActiveRecord provides and how they can be displayed in a user-friendly manner with the help of JavaScript.

What is Validation?

In the context of programming, validation refers to the process of checking and/or proving the validity, relevance, and accuracy of data input. It ranges from checking whether a required age field is filled or not to checking whether a credit card number is valid.

Why is Validation Important?

Validation is very important because it is a way programmers or software developers ensure that an inputted data can be trusted as being accurate and helpful. It saves programmers from inaccurately authorizing unauthenticated users, while also being able to organize user inputs in the desired way without having to go through all the data in the database.

In addition, validation is also useful to avoid edge cases and ensure that programs function within the cases they are designed for. Through data validation, a programmer can save him-/herself from having to write conditionals for all the possible user inputs. Instead, simple data validation will ensure that users can only be able to input data that fulfills certain pre-defined requirements.

This is all to say that although data validation seems like an extra and premium feature that may slow down your development process, it is very crucial as it helps you create robust results.

Types of Validations

Based on the stages they take place, there are two main types of validations — client-side validation and server-side validation.

  • Client-side validation

Client-side validation refers to the process of ensuring that a form’s inputs are of the correct format as when they are being filled out. It ensures that the data inputted by the user matches the requirements set by a programmer before the data is even sent to the server to be processed.

This type of validation is important for a good user experience as it notifies and allows users to fix if any of their inputs are invalid before they send them and have them rejected by the server. As a result, it avoids the delay caused by the trip of the data from the client to the server and back. Not only that, but it is also computationally less-intensive and thus, saves more resources, which is beneficial for both the developer as well as the client.

An example of a client-side validation can be the following:

<form>
<input type="text" name="first_name" required>
</form
<!-- The "required" keyword in the HTML above makes sure that the user does not submit the form without providing a first name. If the user forgets to do so, the form will not go ahead and send the data to the server. Rather, it does not perform any action until the user fills out the required input field -->
  • Server-side validation

In server-side validation, a user’s input is validated by the code stored at the server. The backend code in the server sends back a response to the client regarding the validation of their input, whether it is valid or not. Since clients would not have direct access to the backend’s source code at the server (unlike the front-end HTML), validating on the server-side provides more protection against any malicious attempts. Changing the code at the server is much more difficult than modifying the HTML of a page with the developer tools of a browser.

Why it is good to use server-side validation and client-side validation together

Despite their user-friendliness, client-side validations are vulnerable and unreliable. They could be bypassed by making changes to the front-end code of a given web page. However, if they are combined with server-side validations, their vulnerability would not be as big of a problem as the server-side validations will be able to handle any malicious attempt that may have bypassed the client-side validation.

Therefore, using these two validation techniques together helps a developer set up robust, user-friendly, responsive, and exhaustive validations.

ActiveRecord

As per its definition on its official website, ActiveRecord is “the layer of the system responsible for representing business data and logic”. It “facilitates the creation and use of business objects whose data requires persistent storage to a database.” In simpler terms, it refers to the object-relational mapping system the Ruby programming language and its Rails development framework used to manage database resources.

Along with its other several functions, ActiveRecord provides us with a couple of built-in validation functions, some of which are listed as follows:

acceptance
validates_associated
confirmation
exclusion
format
inclusion
length
numericality
presence
absence
uniqueness
validates_with
validates_each

Using ActiveRecord Validations

ActiveRecord validations are normally applied within the models whose data we want to validate before storing in our databases. They usually follow this general format:

class className < ApplicationRecord
validates :attribute_to_be_validated, validation_method: parameter
end

The following are examples of different validations using built-in helper ActiveRecord validation functions:

class Person < ApplicationRecord
validates :name, presence: true
end
#=> Return this if the name attribute is blank: ActiveRecord::RecordInvalid: Validation failed: Name can't be blankclass Coffee < ApplicationRecord
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end
#=> We can customize the error message returned by failed validations as we wantclass Person < ApplicationRecord
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }
end
#=> Validating the character lengths of different attributesclass Player < ApplicationRecord
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
end
#=> Validating the data types of different attributes

https://guides.rubyonrails.org/active_record_validations.html

Using JavaScript to Display Validation Errors

JavaScript comes into the picture of validations when it comes to displaying the error messages returned by server-side validations. The easiest and most convenient way is to check whether a certain class function returns an error when called in the controller, and if it does, render the error as a JSON. We can then listen to this response from the front-end side and display the error as either alerts or different text forms.

The following is a simple demonstration of how this can be done:

In the model...
class Person < ApplicationRecord
validates :name, presence: true
end
In the controller...
def create
person = Person.create(person_params)
if person
render json: person
else
render person.errors.full_messages
end
end
In the front-end...
fetch(CORRESPONDING_LINK)
.then(r => r.json())
.then()
.catch((error) => {
alert(error);
});

All in all, data validation is an important step in website development, and it can be done both from the client and server’s side. HTML, JavaScript and ActiveRecord can be used synergistically to create a robust validation system for different user inputs.

--

--

Daniel Mekuriaw
Geek Culture

An undergraduate student at Yale University ('24) majoring in Computer Science and Statistics & Data Science