Javascript – Prevent Save

From time to time you might need to add some validation to the save event of an entity, this actually used to be an approach I would use on a regular basis but since the introduction of business rules have found myself doing this less and less. But still, knowing the ability is available is handy.

When you define the onsave event function, you must tick the “Pass execution contact as first parameter” option. (See below)

Having done that you can create an onSave function with code similar to the example I have shown below. Note forgetting the “(context)”, which will take the context parameter allowing you to prevent the save when needed.

function onSave(context) {
  var saveEvent = context.getEventArgs();
  if (Xrm.Page.getAttribute("telephone1").getValue() == null) {
    // *** Note: I am using an alert for testing a notification maybe better!
    alert("Put in a phone number!");

Note: This simple example might be better achieved with a business rule but when you need complex validation that can’t be implemented with a business rule this approach is useful.

Happy Code! J

Leave a Reply

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

You are commenting using your 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