0

Pretty simple goal, I want to make sure a username entered by a user is unique right after they enter it.

I thought I could use Remote Validation, but the page uses knockout.js so the viewmodel is JavaScript. From what I gather I would have to have passed in my model that has the data annotations in VB to use Remote Validation. I can't seem to find examples of this feature that include the html so it's hard to figure out.

How can I accomplish something similar with knockout? I've seen another knockout validation library but don't want to have to add another library to the solution unless it's the only option. It also seems like there should be something better than having an jquery onchange event and using AJAX to call a function on my controller.

I think I have to ultimately call my function on the controller to check the database, it's more the jquery/html attributes I can use to do this as cleanly as possible that I'm struggling with. Thanks for any advice.

1 Answer 1

2

You can subscribe to the change of the username observable on your viewmodel and issue ajax request to the controller that will return the bool.

Something like this

1) Your view model

function registrationViewModel() {
   var self = this;
   self.username = ko.observable();
   self.usernameUniqueue = ko.observable(true);
   self.username.subscribe (function() {
    $.ajax({
        url: '/registration/isusernameuniqueue',
        data: { username: self.userName() },
        type: 'POST',
        success: function(result) {
          self.usernameUniqueue(result);
        }
    });
   });
}

ko.applyBindings(new registrationViewModel())

2) Your view

   <input type="text" data-bind="value: username" />
    <span data-bind="visible: !usernameUniqueue()" style="display:none">user name not uniqueue</span>

3) Your controller

public class Registration : Controller 
{
   [HttpPost]
   public ActionResult IsUsernameUniqueue(string username)
   {
     // make a check here and return true or false...
     return Json(/*true or false*/);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for a thorough example. Seems like essentially same thing as an onchange, but a little more dynamic and more ability to leverage more knockout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.