RubbleFord RubbleFord - 2 months ago 28
jQuery Question

Knockout + Jquery Validate

I'm trying to setup validation with jquery validate, and i've got the viewmodel coming back from the server, mapped to the client and successfully have knockout js binding some data.

I included a called to validate but the validation never triggers, however if I put a class on the input box and then call valid it triggers as expected.

Any ideas?

<script type="text/javascript">
var viewModel;
$(document).ready(function () {
$.ajax({
url: 'Home/GetUserData',
type: 'post',
success: function (data) {
viewModel = ko.mapping.fromJS(data);
viewModel.save = function () { sendToServer(); };
ko.applyBindings(viewModel);
main();
}
});
});

function main() {
$("form").validate({
rules: {
birthPlace: {
required: true,
minlength: 2
}
}
});
}

function sendToServer() {
alert($("form").valid());
}

</script>
}
<h2>@ViewBag.Message</h2>
<form id="nameSubmit" action="">
<div>
The name is: <span id="test" data-bind="text: Name"></span>
</div>
<div>
He's <span id="age" data-bind="text: Age"></span>
</div>
<div>
He's from
<input type="text" id="birthPlace" name="birthPlace"/>
</div>
<div>
<button data-bind="click: save">Click Me</button>
</div>
</form>

Answer

By default jQuery Validate does it's validation on submit. So if knockout is interrupting that, i.e. by not actually triggering the onSubmit event, that would do it. Your best bet may be to do as you were somewhat planning there in your sendToServer function - manually trigger the validation from your knockout submit event:

if (!$('form').valid()){
    $('form').showErrors();
    return false;
}

//otherwise, get on with whatever knockout needs to do
...
return true;
Comments