Bumble
Bumble

Reputation: 557

KO validation group error

I am using a simple login page to capture login and password . While user is clicking forgot password button i validate only login text box .

It is working well in initial page load. initially if i keep user id empty and clicking forgot password triggers validation error and if i correct that still i get null value in error object . I am not sure where this null value came from.

my code follow

Javascript

var loginModule = (function () {
$(document).ready(function () {

     var userName = $('input:text[name=username]').val();
     var password = $('input:text[name=password]').val();

     ko.validation.registerExtenders();
     ko.validation.init();
     ko.applyBindings(new viewmodel(userName, password));

});



var viewmodel = function (username, password) {

    var self = this;

    self.UserName = ko.observable(username).extend({ required: { message: 'User Id is required.' }, minLength: 5, maxLength: 10 });

    self.Password = ko.observable(password).extend({ required: { message: 'Password is required.' }, minLength: 5, maxLength: 10 });

     self.forgotPassword = function () {

        var fperrors = ko.validation.group(self.UserName, { deep: false});

         if (fperrors().length > 0) {

            $('#errorMsg').show();

            fperrors.showAllMessages();

        }

        else {

            //valid code

        }

     };
};

 return {
    viewmodel: viewmodel

}

})();

If i change var fperrors = ko.validation.group(self.UserName, { deep: false});

to var fperrors = ko.validation.group(self.UserName(), { deep: false});

it is not throwing validation error at all.

Html markup

<P>

<p>

<span class="error" data-bind='visible: UserName.hasError, text: UserName.validationMessage'></span>

</p>

<LABEL class="field-label" for="User-id">User ID / alias<EM class=mandatory>*</EM></LABEL><input id="User-id" name="username" class=field-stretch data-bind='value:UserName, valueUpdate: "afterkeydown"'

                        type="text" value="" /></P>

<P>

<p><span class="error" data-bind='visible: Password.hasError, text: Password.validationMessage'></span></p>

<LABEL class=field-label for=Password>Password<EM class=mandatory>*</EM></LABEL>   <input id="Password" name="password" class=field-stretch data-bind='value:Password, valueUpdate: "afterkeydown"' type="password" value="" /></P>

<P class="text-left btn-wrap"><INPUT class="btn-primary" data-bind='click:submit'  value="Logon" type=submit> &nbsp; <INPUT data-bind='click:forgotPassword' class=btn-primary value="Forgotten password?" type=submit>  </P>

can some one assist whats wrong with it?

Upvotes: 0

Views: 619

Answers (1)

Wayne Ellery
Wayne Ellery

Reputation: 7958

I'm not sure why but in my testing I had to pass the observable as an array to get it to work:

var fperrors = ko.validation.group([self.UserName], { deep: false});

http://jsfiddle.net/LHy6h/

Upvotes: 1

Related Questions