onefootswill
onefootswill

Reputation: 4107

Server Side Form Validation with Angular on the Client

I currently have a project where I am converting the client-side stuff to Angular, as I like the bindings aspect of it. Currently, I am doing form validation at the server. After years of doing it at both client and server, I've found my preference is to do it by way of an AJAX request to the server. So, there's no client-side form validation, by design.

It works a treat, with me being able to use jQuery to light up the form with any validation errors that are in the ModelState which is sent back down to the client as json.

Now Angular. I want to keep this implementation, but I feel like I am fighting against the technology to do so. Angular seems to insist on client-side validation.

Is there not a way to, upon receiving an AJAX response with validation errors, tell the Angular validation mechanism what is invalid so I can still just use server-side validation?

Edit I should include a link to a post which I based my implementation on - http://timgthomas.com/2013/09/simplify-client-side-validation-by-adding-a-server/ As you can see, it does not use Angular. It would be nice to take the Server-side aspects of it and get it working with AngularJs

Thanks

Upvotes: 1

Views: 1983

Answers (1)

George
George

Reputation: 6739

This is one way to do it, depending on how much you're willing to change in your current code and assuming some things.

Let's you have a form like this

<form name="form" novalidate ng-submit="update(form)">
    <input type="text" ng-model="Input" name="Input"/>
    <button type="submit">Save</button>
</form>

Then your update function should look like this

function update(form) {
    testResource.save($scope.Input)
        .$promise
        .then(function (response) {
            console.log("Success");
        })
        .catch(function (response) {
            console.log("fail");
            for (var i = 0; i < response.data.length; i++) {
                form[response.data[i].Name].$setValidity(response.data[i].Error, false);
            }
        });
}

The data in the failed response would be structured like this

[{ Name: "Input", Error: "required" }];

This should allow you to do all the validation on the server and pass it down to angular to handle.

Going into a bit more detail, on the submit function you're sending the angular form up to the controller, then when the angular resource gets a bad response you add the error to the form property that has an error. This would mean the name of your input would have to be the same as the Name you pass down from the bad response.

Upvotes: 5

Related Questions