Add validation for year field in Dynamics 365 using JavaScript

Problem:  While working on a Dynamics 365 Implementation, I realized that Dynamics CRM doesn’t have any out-of-the-box validation for year fields. In order to validate the year field we added a JavaScript function in the form.

Solution :

Follow the steps below to perform the validation.

  • To add validation to year field we need to first retrieve that value from the page using XRM object.
  • Add a JavaScript file to the Entity form.

1

2

3

  • Add the below code to the Javascript file
//Method called on year field change
function checkfield() {
    var year = Xrm.Page.getAttribute("yearofpassing").getValue(); //get current value of field
    var check = IsYear(year);
    if (!check) {
 Xrm.Page.getControl("yearofpassing").setNotification("Year should be in format XXXX");
    }
}
//Regex to check year validity
function IsYear(year) {
  // alert("entered IsYear method");
    return /^\d{4}$/.test(year);
}
  • Add the function “Checkfield’ on field change

4

  • On entering an invalid year,  gives an error.

6

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s