NPehrsson
NPehrsson

Reputation: 1548

Knockoutjs validation and server validation

Hi I'm kind of new to Knockoutjs, I am in the scenario where I want to post a form where I have for example an email address, there is an requirement that the email address needs to be unique.

On the server I check if the email address is unique or not and then returns an validationjson class for example

{ isEmailUnique: false, isPasswordStrongEnough: true; }

How can I with knockoutjs validation show these errors in a neat way?

Upvotes: 1

Views: 5156

Answers (2)

Tom W Hall
Tom W Hall

Reputation: 5283

I'm a bit late, but for my 2 cents worth, I would take a more generic approach such as returning a standard JSON serialized AjaxResult class from your server endpoints (such as /Register) with properties such as Data (an arbitrary container used for, for example, an updated model to re-bind with the mapping plugin), and a collection of validation message strings, etc. Then you could have an HTML validation summary which is bound to an ObservableArray and push / map the messages from your Ajax result into there. This is essentially what I've been doing with Knockout and it works nicely.

Upvotes: 2

Mikael Östberg
Mikael Östberg

Reputation: 17156

I would use two different server side validators for this, since they affect different observables in the view model.

Originally taken from the knockout validation readme

ko.validation.rules['isEmailUnique'] = {
   validator: function(val, param){
      var isValid = true;

      $.ajax({
          async: false,
          url: '/validation/isEmailUnique',
          type: 'POST',
          data: { value: val, param: param },
          success: function(response){
                 isValid = response === true;              
          },
          error: function(){
                 isValid = false; //however you would like to handle this              
          }
       });

       return isValid;
  },
  message: 'The Email is not unique'
};              

Then on the server you need to create an endpoint that accepts POST requests where you perform your lookup and then return true or false depending on the result of the query.

To use the above validator

this.email = ko.observable()
   .extend({ 
      isEmailUnique: { 
         message: 'Something else perhaps? It will override the message in the validator' 
      } 
   });

You can use the very same thing for the password strength validation.

Using validators like this will fire validation when the observable changes, which can be a useful way to do validation.

Upvotes: 4

Related Questions