Power Portals / Power Pages

Power pages – Date field custom validation using Jquery

Introduction

Power Pages (formerly Power Apps Portals) provide a low-code platform to build web applications with seamless integration to Microsoft Dataverse and Dynamics 365. When working with forms in Power Pages, ensuring proper data validation is crucial to maintaining data integrity.

In this blog, we will discuss how to implement custom validation for a Date of Birth (DOB) field using jQuery. This validation ensures that users can only select past dates, preventing future dates from being submitted.

Why Custom Validation?

While Power Pages provide built-in validation options, sometimes custom validation is needed for more specific requirements. For example:

  • Ensuring DOB is always in the past
  • Validating date formats before submission
  • Enhancing user experience by providing immediate feedback

Using jQuery, we can extend Power Pages validation without modifying backend logic.

Implementing Custom DOB Validation Using jQuery

To achieve this, we will:

  1. Check if Power Pages’ validation system (Page_Validators) exists
  2. Create a custom validator dynamically
  3. Add validation logic to ensure the date is in the past
  4. Handle the error message for better user experience
$(document).ready(function () {
    try {
        if (typeof (Page_Validators) === 'undefined') return;

        // Ensure the Date of Birth field exists
        if (!$("#new_dateofbirth").length) return;

        // Create new DOB validator
        var dobValidator = document.createElement('span');
        dobValidator.style.display = "none";
        dobValidator.id = "dobValidator";
        dobValidator.controltovalidate = "new_dateofbirth";
        dobValidator.errormessage = "<a href='#new_dateofbirth_label'>Date of birth should be in the past.</a>";
        dobValidator.validationGroup = "";
        dobValidator.initialvalue = "";

        // Evaluation function for validation
        dobValidator.evaluationfunction = function () {
            var dobValue = $("#new_dateofbirth").val();
            if (!dobValue) return false; // Ensure the field is not empty
            
            var dob = new Date(dobValue);
            var today = new Date();
            
            if (isNaN(dob.getTime()) || dob.getTime() > today.getTime()) {
                return false;
            }
            return true;
        };

        // Add the dobValidator to the page’s validators array
        Page_Validators.push(dobValidator);

        // Attach event handler for validation summary link
        $("a[href='#new_dateofbirth_label']").on("click", function () {
            scrollToAndFocus('new_dateofbirth_label', 'new_dateofbirth');
        });
    } catch (e) {
        console.error("Error during DOB validation:", e);
    }
});

Explanation of the Code

1. Document Ready Function

Ensures that the script runs only after the page has fully loaded:

$(document).ready(function () {

2. Checking If Validation System Exists

If Page_Validators is not present, the script exits:

if (typeof (Page_Validators) === 'undefined') return;

3. Ensuring the Date Field Exists

Prevents unnecessary execution if the field does not exist:

if (!$("#new_dateofbirth").length) return;

4. Creating a Custom Validator

Dynamically creates a new <span> validator for the new_dateofbirth field:

var dobValidator = document.createElement('span');
dobValidator.style.display = "none";
dobValidator.id = "dobValidator";
dobValidator.controltovalidate = "new_dateofbirth";
dobValidator.errormessage = "<a href='#new_dateofbirth_label'>Date of birth should be in the past.</a>";

5. Defining the Validation Logic

Ensures the entered date is valid and in the past:

dobValidator.evaluationfunction = function () {
    var dobValue = $("#new_dateofbirth").val();
    if (!dobValue) return false;
    
    var dob = new Date(dobValue);
    var today = new Date();
    
    if (isNaN(dob.getTime()) || dob.getTime() > today.getTime()) {
        return false;
    }
    return true;
};

6. Adding the Validator to Power Pages

Registers the custom validation function with Power Pages:

Page_Validators.push(dobValidator);

7. Handling Error Messages Gracefully

When the user clicks the error message, they are smoothly scrolled to the field:

$("a[href='#new_dateofbirth_label']").on("click", function () {
    scrollToAndFocus('new_dateofbirth_label', 'new_dateofbirth');
});

8. Error Handling

Captures any errors and logs them to the console:

} catch (e) {
    console.error("Error during DOB validation:", e);
}

Key Benefits of This Approach

✅ Ensures only past dates can be selected in the Date of Birth field.
✅ Uses Power Pages’ built-in validation system, ensuring a seamless experience.
✅ Provides a clickable error message, improving user accessibility.
Handles errors gracefully, preventing page crashes.
✅ Improves data integrity by preventing invalid submissions.

Enhancements You Can Add

🚀 Check for a minimum age requirement (e.g., 18+ for adult registrations).
🚀 Show real-time validation feedback (display an inline error message before form submission).
🚀 Extend validation for different date formats to ensure proper input handling.

Conclusion

Using jQuery to customize Power Pages validation allows for a more user-friendly and reliable data entry process. With the method demonstrated in this article, you can effectively enforce Date of Birth restrictions while integrating smoothly with Power Pages’ existing validation system.

Leave a Reply