Skip to main content

Notifications

Community site session details

Community site session details

Session Id :

How to Add Regular Expression Validation to a D365 Form Field Using JavaScript

Dominik Stalzer | primeone Profile Picture Dominik Stalzer | p... 68

Ensuring data quality in Microsoft Dynamics 365 (D365) is essential, and one of the best ways to enforce input validation is by using regular expressions (regex) in JavaScript. This article will walk you through how to add regex validation to a form field in D365, preventing invalid user input.




Why Use Regex in D365?
Regular expressions allow us to define flexible validation rules for form fields. For example, you may want to restrict a field to only alphanumeric characters, enforce a minimum length, or ensure a phone number follows a specific pattern.

Implementing Regex Validation in D365
To apply regex validation to a field in a D365 form, follow these steps:
In my case, I applied this to the out-of-the-box (OOTB) Business Phone form field to ensure proper phone number formatting.



Add the JavaScript Code
Below is an example function that validates a field’s value using regex:

/**
* Author: Dominik Stalzer
* Company: primeone business solutions gmbh
* Contact Email: dominik.stalzer@primeone.at
* Website: primeone.at
*/
function pbs_regexCheckValue(executionContext, fieldname) {
    var formContext = executionContext.getFormContext();
    var fieldAttribute = formContext.getAttribute(fieldname);
    if (fieldAttribute) {
        var fieldAttributeValue = fieldAttribute.getValue();
        // regex to allow numbers at least 7 digits long, optionally starting with '+'
        const phoneRegex = /^\+?\d{7,}$/;
        if (fieldAttributeValue) {
            if (fieldAttributeValue.match(phoneRegex) != null) {
                formContext.getControl(fieldname).clearNotification();
            }
            else {
                formContext.getControl(fieldname).setNotification("Invalid phone number. Use only digits, optionally starting with '+', and at least 7 characters.");
            }
        }
    }
}


  • Open the form’s properties.
  • Choose the field where validation is needed.
  • Under Events, select Event Handler
  • Select Add library and add the JavaScript file.



  • Pass the function pbs_regexCheckValue and the field’s logical name as a parameter.



Let's check:





I hope these instructions have helped some of you.


Comments