How to Validate Date Fields in Odoo 13

Validating Input Fields in Odoo

by Hafiz Junaid

In Odoo, especially for portal users, validating input fields and ensuring the data is in the correct format is common. One such case is when we need to validate a date field, redirect users if the date is invalid, and change the date format for a better user experience on a portal screen.

This blog explains how to:

  • Raise validation on a date field through a controller and redirect users to a different page if the date is invalid.
  • Using XML and JavaScript, change the date format from mm/dd/yyyy to dd/mm/yyyy on the portal screen.

Let's break down the implementation in Odoo 13.

Step 1: Validate Date Input through Controller

In Odoo, you can perform validation using controllers, especially when users submit forms from the portal. In this case, we are validating a birthday field and redirecting users to a different page if the date is invalid (e.g. if the person is over 100 years old).

Python Code (Controller)

Here’s a Python method in the controller that validates the date and redirects to a different page if the date is invalid.

from odoo import http
from odoo.http import request
from datetime import datetime
class NewJoinerPortal(http.Controller):
    @http.route(route='/new-joiner/form/<string:access_token>', type='http', auth='public', website=True)
    def new_joiner_form(self, access_token, **post):
        hr_new_joiner_id = request.env['hr.new.joiner'].sudo().search([(access_token, '=', access_token)])
        birthday = post.get('birthday')
        # Validate the birthday
        valid_birthday = hr_new_joiner_id._verify_date(birthday)
        if not valid_birthday:
            # Redirect if the date is invalid
            return request.redirect('/new-joiner/form/%s?birthday=1' % (hr_new_joiner_id.access_token))
        # If valid, parse the date to the correct format for saving in the database
        birthday = datetime.strptime(birthday, '%d/%m/%Y')
        # Render the form again if no redirection is needed
        return request.render('your_module.new_joiner_form_template', {
            'hr_new_joiner_id': hr_new_joiner_id,
            'birthday': birthday,
        })
    def _verify_date(self, date_str):
        """Verify if the birthday is valid."""
        day, month, year = date_str.split('/')
        current_year = datetime.now().year
        # Check if the person is older than 100 years
        if int(year) < current_year - 100:
            return False
        return True
Explanation
_verify_date method

This method validates if the person’s birth year is over 100 years ago. If it is, it returns True, indicating an invalid date.

Redirection

If the birthday is invalid, the controller redirects to the same form with a query string (birthday=1), which will be used to display an error message.

Valid Birthday

If the birthday is valid, the date is parsed from dd/mm/yyyy format to be used or stored in the database.

Step 2: Display Validation Error on Portal

When the birthday is invalid, the page will be reloaded with the URL parameter birthday=1. This will trigger an error message on the portal form.

XML Code for Error Message

In the form view, you can check for the birthday parameter to display a validation message to the user.

<div t-if="request.params.get('birthday')" class="alert alert-danger mt-2 pt-2 pb-2" 
role="alert">
    Invalid birthday.
</div>
Explanation
t-if="request.params.get('birthday')"

This line checks if the birthday parameter exists in the URL. If it does, it means the birthday was invalid, and the error message "Invalid birthday" is displayed in a red alert box.

Step 3: Change Date Format in Portal

By default, the date input format in many systems is mm/dd/yyyy. However, you may want to change this format to dd/mm/yyyy for the user. Here’s how to implement this change using XML and JavaScript.

XML Code for Input Field

In the form, we will use a <input> field for the birthday, which the user will interact with.

<input type="text" name="birthday" id="birthday" required="required"
class="form-control new_joiner_form_date_picker" t-att-value="birthday" />
Explanation
class="new_joiner_form_date_picker"

This class will be used by JavaScript to apply the date picker with the desired format.

JavaScript Code for Date Format

Use JavaScript to apply the date picker with the desired dd/mm/yyyy format.

$(document).ready(function () {$('.new_joiner_form_date_picker').datepicker({
   dateFormat: // Set custom date format
   autoclose: true, // Close the datepicker automatically after selecting a date
   todayHighlight: true // Highlight today's date
  });
});
Explanation
dateFormat: 'dd/mm/yy'

This sets the format of the date picker to day/month/year.

autoclose: true

This ensures that the date picker will automatically close after a date is selected.

todayHighlight: true

Highlights the current date in the date picker for ease of use.

Conclusion

By following this tutorial, you have successfully learned how to:

  • Raise validation on a date field through a controller in Odoo 13.
  • Redirect the user to a different page when the date is invalid.
  • Customise the date format on a portal screen from mm/dd/yyyy to dd/mm/yyyy.

These techniques enhance the user experience by enforcing correct date inputs and providing helpful error messages in case of mistakes.

Need more development tips?

Stay tuned to our blog.

Hafiz Junaid 23 September, 2024
Archive
Sign in to leave a comment
How to Upgrade or Downgrade Python Packages in Ubuntu