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>
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;
There is now a knockout jQuery validate binding, which I find very useful:
https://github.com/Knockout-Contrib/Knockout-Validation
I'd like to recommend against using jQuery validate with knockout. The reason is that jQuery validate binds to the DOM, while knockout recommends working with the view model. This will lead to problems once you start adding more dependencies on the validation, such as preventing certain behavior if data is invalid, but you still need to retain the data. Go for knockout validation, it does the job very well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With