Validating Data Requests Using Cloud Code for Data

Validating Data Requests Using Cloud Code for Data

Using the pre-processing events, you can easily validate your request results against any custom rules. To facilitate the process, Cloud Code provides a number of built-in validators that check for common data patterns.

  • Everlive.Validation.validateEmail(value) - checks whether the given email is in a valid format;
  • Everlive.Validation.validateUsZipCode(value) - validates the given argument is a valid US Zip Code;
  • Everlive.Validation.validateUsSocialSecurity(value) - verifies if the given string is a valid US Social Security number;
  • Everlive.Validation.validateInteger(value) - checks if the specified string is a valid integer;
  • Everlive.Validation.validateNumeric(value) - checks whether its argument represents a numeric value;
  • Everlive.Validation.validateAlphaNumeric(value) - verifies if the argument contains only alpha numeric characters.

Validating user email and returning an error

You can use the built-in Everlive.Validation.validateEmail(value) function to check whether an email part of the request is valid, and use the Everlive.Response.sendError function to return an error in case the validation fails. Note that the sendError function accepts three arguments errorMessage, errorCode and statusCode. For example, if we want to check whether an email is in the correct format, and return an error with errorCode 131 with status 500 you can execute the following code snippet:

Everlive.Events.beforeCreate(function (request, context, done) {
    var email = request.data.Email;
    var isValid = email && Everlive.Validation.validateEmail(email);
    //check whether the email is not null and whether it is valid
    if (!isValid) {
        Everlive.Response.setErrorResult('The "Email" field must be a valid email address.', 131, 500);
    }
    done();
});
Once you define the script above in your cloud code for a content type that contains an Email field and execute a read request, you will get the following response:
{
    "message": "The \"Email\" field must be a valid email address.",
    "errorCode": 131
}
Start a free trial Request a demo
Contact us: +1-888-365-2779
sales@telerik.com
Copyright © 2016-2017, Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.