Hi All,
The onSubmit event is not really suitable for doing validation steps, as if you've set the form to be not be submittable, it will no longer be called. For field validation, it's much better to use the onValidate event handler instead. This event handler will be called every time the form is validated, which will still occur if the form is not submittable.
So for a simple validator that prevents form submission:
MktoForms2.loadForm("//my-pod-name.marketo.com", "MyMunchkinID", myFormId, function(form){
form.onValidate(function (valid){
if(form.getVals().MyFieldName != "mycondition"){
form.submitable(false);
}else{
form.submitable(true);
}
});
});
You might also want to play around with the form.showErrorMessage API to display an error when your custom validator fires.
I also saw some advice in this thread about how to get the form object. The best way to get a reference to the form object on a page (outside of the initial render callback) is to use the MktoForms2.whenReady handler.
MktoForms2.whenReady(function (form){
form.getVals(); //do whatever you want here with the form.
});
The advantage of this method over other ways to get the form object (there are many) is that it is smart about the form lifecycle. If the form has not yet been rendered, then your code in whenReady function will be deffered until it is rendered. If the form has already been rendered, it will be called immediately. This will save you from having to make sure that your form is rendered before trying to get its form object.
I'm going to work with our web publishing team to get the documentation on developer.marketo.com updated, with a better validation example and documentation on the MktoForms2.whenReady function to help avoid these same confusions in the future.