How to Set and Clear Notification for Non-Mandatory Field Using JavaScript in Power Apps

How to Set and Clear Notification for Non-Mandatory Field Using JavaScript in Power Apps

In Power Apps and Dynamics 365 Model-Driven Apps, there are situations where you want to guide users with validation messages without making a field mandatory.

Using JavaScript, you can display notifications on fields dynamically and remove them when the required condition is satisfied. This improves user experience while maintaining business validations.

Why Use Field Notifications?

Set a Notification

Use the setNotification() method to display a message on a field.

function setFieldNotification(executionContext)
{
    var formContext =
        executionContext.getFormContext();

```
formContext.getControl("new_comments")
           .setNotification(
               "Please enter comments before proceeding.",
               "comments_notification"
           );
```

} 

The notification appears beside the field and alerts users about the required action.

Clear a Notification

Once the validation condition is satisfied, remove the notification using clearNotification().

function clearFieldNotification(executionContext)
{
    var formContext =
        executionContext.getFormContext();

```
formContext.getControl("new_comments")
           .clearNotification(
               "comments_notification"
           );
```

} 

Combined Example

You can dynamically set or clear notifications based on field values.

function validateComments(executionContext)
{
    var formContext =
        executionContext.getFormContext();

```
var comments =
    formContext.getAttribute("new_comments")
               .getValue();

if(!comments)
{
    formContext.getControl("new_comments")
               .setNotification(
                   "Comments are recommended.",
                   "comments_notification"
               );
}
else
{
    formContext.getControl("new_comments")
               .clearNotification(
                   "comments_notification"
               );
}
```

} 
Important: Always use unique notification IDs when calling setNotification() and clearNotification() to ensure proper notification management.

Implementation Steps

  1. Create a JavaScript Web Resource.
  2. Add the script to the form.
  3. Register the function on Form Load or On Change events.
  4. Pass execution context.
  5. Save and publish customizations.
  6. Test notification behavior.

Common Use Cases

Best Practices

Key Takeaways