Quantcast
Viewing latest article 3
Browse Latest Browse All 5

Build a Single Page Application with the HotTowel SPA Template – Part Three – Adding Validation

A feature that’s highly appreciated by users and developers is client side validation. ASP .NET provides us with a very useful set of attributes, we can annotate our classes with, to specify validation rules on model properties. The good news is that this meta-information is available on the client side with Breeze JS. I’m going to show you how we can set up client validation in Single Page Application, in the Update and Create views, in under 5 minutes.

Adding validation attributes to our model

First we’re going to set up validation on the server side. We add validation attributes to our model properties. ASP .Net provides us with this attributes out of the box – they come from the System.ComponentModel.DataAnnotations namespace from the assembly with the same name. We can also create custom validation attributes, but we’ll stick with the regular ones for this example. We add the [Required] attribute to the Name,Description and Address properties of our RestaurantBrief model. The validation rule will be inherited in Restaurant.

public class RestaurantBrief
{
	[Key]
	public int Id { get; set; }

	[Required]
	public string Name { get; set; }

	[Required]
	public string Address { get; set; }

	[Required]
	public string Description { get; set; }
}

public class Restaurant : RestaurantBrief
{
	//[Key]
	//[Required]
	//public string Id { get; set; }

	//[Required]
	//public string Name { get; set; }

	//[Required]
	//public string Address { get; set; }

	//public string Description { get; set; }

	public string CoverPhoto { get; set; }

	public double Rating { get; set; }

	public Location Location { get; set; }

	public Guid OwnerId { get; set; }
}

Getting the validation errors on the client side

On the client side, when we request an update or addition of an entity with the EntityManager, if the validation rules are not satisfied we’ll have an error as a result. In the error object we have the list of the entities that failed to be updated (entitiesWithErrors). For each entity we have the list of the validation errors in the entityAspect property. The code below shows how we can get all the validation errors for an entity.

	var entityValidationErrors = entity.entityAspect.getValidationErrors();

To get all the errors for all the failed entities from the error object we can do the following (assuming we have a validationErrors property in our viewmodel).

function saveFailed(error) {
	toastr.error("Save failed");
	error.entitiesWithErrors.map(function (entity) {
		entity.entityAspect.getValidationErrors().map(function (validationError) {
			vm.validationErrors.push(validationError);
		});
	});
}

When we edit an entity, it would be the only entity we have in our context. That’s why we can create a method to get the first error by property name:

function getPropertyError(propertyName) {
	var validationErrors = ko.utils.arrayFilter(vm.validationErrors(), function (validationError) {
		return validationError.propertyName == propertyName;
	});

	if (validationErrors.length > 0)
		return validationErrors[0].errorMessage;
	else
		return '';
}

We can then bind to this function to show and hide the error to the client.

<section>
	<div><a class="backLink" data-bind="click: goBack">< Back</a></div>
	<table class="restaurant" data-bind="with: editableRestaurant">
		<tbody>
			<tr>
				<td><img class="restaurant-cover" alt="" data-bind="attr: { src: '/Content/RestaurantPhotos/' + CoverPhoto(), alt: Name }" /></td>
				<td>
					<label for="description">Description</label> <textarea id="description" rows="8" data-bind="value: Description"></textarea>
					<div class="propertyError" data-bind="text: $parent.getPropertyError('Description')"></div>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<label for="name">Name</label> <input class="restaurant-name" id="name" type="text" data-bind="value: Name" />
					<div class="propertyError" data-bind="text: $parent.getPropertyError('Name')"></div>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<label for="address">Address</label> <input id="address" type="text" data-bind="value: Address" />
					<div class="propertyError" data-bind="text: $parent.getPropertyError('Name')"></div>
				</td>
			</tr>
		</tbody>
	</table>
	<button type="button" data-bind="click: saveChanges">Save</button>
</section>

That’s it. We now have client validation in our form. But that’s not all. We can extend the validation by defining validation rules on the client side. To see how we can extend the validation please refer to the documentation on Breeze’s website http://www.breezejs.com/documentation/validation.

Source Code

You can download a working example of client side validation with BreezeJS and the WebAPI below.

Other articles in this series

The post Build a Single Page Application with the HotTowel SPA Template – Part Three – Adding Validation appeared first on Georgi Stavrev.


Viewing latest article 3
Browse Latest Browse All 5

Trending Articles