Perform Custom Validations using Form Script in AgileApps

Overview

  • This article provides details about how to perform custom validations using Form Script when a form is saved. This is achieved using the on-save form script capability of a form.
  • Form Script allows you to specify JavaScript/JQuery code to execute, when a Form is loaded or saved. JavaScript code can be invoked at these form-level events on-load and on-save
  • In this article, we will discuss about on-save.
  • On-save event happens when a user clicks the Submit button on a form. At this event, optionally you can perform front-end validations before sending the data to the server and return false to cancel the save action.

Prerequisites

To perform the actions here, you should have a basic understanding of JavaScript, and/or jQuery. Also, you should have basic knowledge of accessing form elements.

Procedure

To add your custom script for the new UI

  • Go to Settings > Objects.
  • Select the object.
  • Click Forms.
  • Select a layout.
  • Click Form Scripts.
  • Click Edit.
  • Click the New UI Script tab.
Note: This is an example for your reference where we are validating Name (text-field) with some specific criteria; for example, name should contain only letter and space.

Write the following code in the Reusable Script Functions section:

function validateName() {

      var form = _sdForm;

      var name = getTextFieldValue(form, ‘user_name’); // prefer to use JavaScript Platform API or you can do it through fieldname directly (Ex. _sdForm.user_name.value).

      var regex = new RegExp(/^[A-Za-z\s]+$/);

      if (regex.test(name)) {

         return true;

} else {

         // Alert user with validation message.

alert(‘Name should contain only letter and space!’);

         // Cancel the SAVE action of the form by returning false.

return false;

}

}

Write the following code in On Save Script section:

return validateName();

Summary

  • Used JavaScript Platform API to get the value of the target field.
  • Validating the field value.
  • Return false to prevent the form save action, if validation failed and prompt the error to the user.

Considerations

We recommend you to access the field through JavaScript Platform API. However, we do not restrict you from using it.

**Note:** Here, we declare the method validateName() in the Reusable Script Functions tab and call it in the On Save Script tab. You can also declare the method in On Save Script tab and then call it. Or, you can write only the method body in the On Save Script Tab. This requires no method declaration and calls.