Validating Data Requests Using Cloud Code for Data

Using pre-processing events, you can validate 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)—validates the format of the email address you pass.
  • Everlive.Validation.validateUsZipCode(value)—checks if the argument is a valid US Zip Code.
  • Everlive.Validation.validateUsSocialSecurity(value)—checks if the argument 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 if the argument represents a numeric value.
  • Everlive.Validation.validateAlphaNumeric(value)—verifies if the argument contains only alphanumeric characters.

Validating User Email and Returning an Error

You can use the built-in Everlive.Validation.validateEmail() function to check whether an email address coming in with the request is valid. If you combine it with the Everlive.Response.setErrorResult() function, you can return an error in case the validation fails.

The setErrorResult() function accepts three arguments. Only the first is mandatory.

  • errorMessage, which is a custom message that you want to return;
  • errorCode, which is a custom error code;
  • statusCode, which is the HTTP status code that you want the server to return if you don't want to go with the default 400.

The following code checks whether an email is in the correct format and returns an error if it isn't.

<code>Everlive.Events.beforeCreate(function (request, context, done) {
    var email = request.data.Email;
    //check if the email is not null and if it's valid
    var isValid = email && Everlive.Validation.validateEmail(email);
    if (!isValid) {
        Everlive.Response.setErrorResult('The "Email" field must be a valid email address.', 131, 500);
    }
    done();
});

Define the code above in the Cloud Code of a content type that contains an Email field and you will get the following response on each create request containing an invalid email address:

{
    "message": "The \"Email\" field must be a valid email address.",
    "errorCode": 131
}

See Also

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.