Validate and modify data in Mobile Services by using server scripts
This topic shows you how to leverage server scripts in Windows Azure Mobile Services. Server scripts are registered in a mobile service and can be used to perform a wide range of operations on data being inserted and updated, including validation and data modification. In this tutorial, you will define and register server scripts that validate and modify data. Because the behavior of server side scripts often affects the client, you will also update your HTML app to take advantage of these new behaviors.
This tutorial walks you through these basic steps:
- Add string length validation
- Update the client to support validation
- Add a timestamp on insert
- Update the client to display the timestamp
This tutorial builds on the steps and the sample app from the previous tutorial Get started with data. Before you begin this tutorial, you must first complete Get started with data.
Add validation
It is always a good practice to validate the length of data that is submitted by users. First, you register a script that validates the length of string data sent to the mobile service and rejects strings that are too long, in this case longer than 10 characters.
-
Log into the Windows Azure Management Portal, click Mobile Services, and then click your app.

-
Click the Data tab, then click the TodoItem table.

-
Click Script, then select the Insert operation.

-
Replace the existing script with the following function, and then click Save.
function insert(item, user, request) {
if (item.text.length > 10) {
request.respond(statusCodes.BAD_REQUEST, {
error: "Text cannot exceed 10 characters"
});
} else {
request.execute();
}
} This script checks the length of the TodoItem.text property and sends an error response when the length exceeds 10 characters. Otherwise, the execute function is called to complete the insert.
Note
You can remove a registered script on the Script tab by clicking Clear and then Save.
Update the client
Now that the mobile service is validating data and sending error responses, you need to update your app to be able to handle error responses from validation.
-
Run one of the following command files from the server subfolder of the project that you modified when you completed the tutorial Get started with data.
- launch-windows (Windows computers)
- launch-mac.command (Mac OS X computers)
- launch-linux.sh (Linux computers)
Note
On a Windows computer, type `R` when PowerShell asks you to confirm that you want to run the script. Your web browser might warn you to not run the script because it was downloaded from the internet. When this happens, you must request that the browser proceed to load the script.
This starts a web server on your local computer to host the app.
-
Open the file app.js, then replace the $('#add-item').submit() event handler with the following code:
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false })
.then(refreshTodoItems, function(error){
alert(JSON.parse(error.request.responseText).error);
});
}
textbox.val('').focus();
evt.preventDefault();
}); -
In a web browser, navigate to http://localhost:8000/, then type text in Add new task and click Add.
Notice that the operation fails and error handling displays the error response in a dialog.
Add a timestamp
The previous tasks validated an insert and either accepted or rejected it. Now, you will update inserted data by using a server script that adds a timestamp property to the object before it gets inserted.
-
In the Scripts tab in the Management Portal, replace the current Insert script with the following function, and then click Save.
function insert(item, user, request) {
if (item.text.length > 10) {
request.respond(statusCodes.BAD_REQUEST, {
error: 'Text length must be under 10'
});
} else {
item.createdAt = new Date();
request.execute();
}
} This function augments the previous insert script by adding a new createdAt timestamp property to the object before it gets inserted by the call to request.execute.
Note
Dynamic schema must be enabled the first time that this insert script runs. With dynamic schema enabled, Mobile Services automatically adds the createdAt column to the TodoItem table on the first execution. Dynamic schema is enabled by default for a new mobile service, and it should be disabled before the app is published.
-
In the web browser, reload the page, then type text (shorter than 10 characters) in Add new task and click Add.
Notice that the new timestamp does not appear in the app UI.
-
Back in the Management Portal, click the Browse tab in the todoitem table.
Notice that there is now a createdAt column, and the new inserted item has a timestamp value.
Next, you need to update the app to display this new column.
Update the client again
The Mobile Service client will ignore any data in a response that it cannot serialize into properties on the defined type. The final step is to update the client to display this new data.
-
In your editor, open the file app.js, then replace the refreshTodoItems function with the following code:
function refreshTodoItems() {
var query = todoItemTable.where(function () {
return (this.complete === false && this.createdAt !== null);
});
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">')
.prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.text))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
});
} This displays the date part of the new createdAt property.
-
In your editor, open the style.css file, and replace the styles on the item-text class with the following:
.item-text { width: 70%; height: 26px; line-height: 24px;
border: 1px solid transparent; background-color: transparent; }
.timestamp { width: 30%; height: 40px; font-size: .75em; } This resizes the textbox and styles the new timestamp text.
-
Reload the page.
Notice that the timestamp is only displayed for items inserted after you updated the insert script.
-
Again in the refreshTodoItems function, replace the line of code that defines the query with the following:
var query = todoItemTable.where(function () {
return (this.complete === false && this.createdAt !== null);
}); This function updates the query to also filter out items that do not have a timestamp value.
-
Reload the page.
Notice that all items created without timestamp value disappear from the UI.
You have completed this working with data tutorial.
Next steps
Now that you have completed this tutorial, consider continuing on with the final tutorial in the data series: Refine queries with paging.
For more information, see Work with server scripts.