Make a standard POST form validation in Knockout - mvvm

To allow to make validation of form before submit,
I want to make a simple HTTP POST submit from the Submit method i defined.
Code of the view :
<form data-bind="submit: BaseSubmit" id="FormId">
<!-- Some rows ... -->
<button type="submit">Create</button>
</form>
And of the JS behavior
this.viewModel.BaseSubmit =
function(formElements) {
//Here the code to make the submit redirection
};
Is this possible ?
Thanks by advance.

Upon successful validation, make sure and return true from your binding handler:
this.viewModel.BaseSubmit =
function(formElements) {
if (/* validation is successful */) {
return true;
} else {
/* handle validation errors */
}
};
Example: http://jsfiddle.net/CCNtR/22/
From the documentation:
By default, Knockout will prevent the event from taking any default action. For example if you use the event binding to capture the keypress event of an input tag, the browser will only call your handler function and will not add the value of the key to the input element’s value. A more common example is using the click binding, which internally uses this binding, where your handler function will be called, but the browser will not navigate to the link’s href. This is a useful default because when you use the click binding, it’s normally because you’re using the link as part of a UI that manipulates your view model, not as a regular hyperlink to another web page.
However, if you do want to let the default action proceed, just return true from your event handler function

Related

Custom Form Layout Validation

I want to have my own validation flow, with custom layout and message.
By default, the validation from the form builder put all the error message beside the input field. And it will validate all fields at once after submit.
I want to validate field by field after submitting, and error message is displayed in the same place for all the input fields (beside the submit button/on top of the form).
Currently I'm trying custom form layout with "ASCX" type. Is it possible to do all the validation in the back-end code ".cs"?
Or I must inject java script at the custom form layout design in source mode?
Or there is any better way to do it?
In HTML layout type you can place validation macros anywhere you need -> $$validation:FirstName$$
You can also specify a validation that executes without submitting the form - example -> http://devnet.kentico.com/articles/tweaking-kentico-(2)-unique-fields
Anyway, with the validation macro above you can move the error message wherever you want.
In your online form, go to Layout and enter your layout markup manually using HTML and the macros for form field values, labels and validation. There you can specify where all your form elements will go on the form, even the button.
If you want to have custom CS for your validation of that form, you're better off creating a custom event handler for the form before insert. See documentation below:
Custom event handler
Form Event handler
using CMS;
using CMS.DataEngine;
using CMS.OnlineForms;
using CMS.Helpers;
// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomFormModule))]
public class CustomFormModule : Module
{
// Module class constructor, the system registers the module under the name "CustomForms"
public CustomFormModule()
: base("CustomForms")
{
}
// Contains initialization code that is executed when the application starts
protected override void OnInit()
{
base.OnInit();
// Assigns a handler to the Insert.After event
// This event occurs after the creation of every new form submission
BizFormItemEvents.Insert.After += Insert_After;
}
private void Insert_After(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
if (e.Item.TypeInfo.ObjectType.ToLower().Contains("bizform.codename"))
{
//do some work or form validation
}
}
}

How do I add onsubmit or onclick validation logic to my Lift form using CSS binding?

I have a form working with CSS selector binding and Scala-side validation. Now I want to add javascript validation either via my own jQuery code that I call or else the built-in commands like JsIf.
Here is my current code:
def create = {
"#description" #> SHtml.textarea(maintRV.is.description.get,
name => maintRV.is.description(name) ) &
"#submit" #> SHtml.onSubmitUnit(processSubmit)
}
How can I add onclick or onsubmit behavior to the SHtml.onSubmitUnit binding? I have already used Ajax forms in other parts of my code, but for this page that seems like overkill. I don't mind a regular form submit. I just want to add client-side validation.
I've combed SimplyLift, Exploring Lift and the groups and can't find it.

How to use form validation in a form with a zone attribute?

I have a big problem with Tapestry 5.3.6..
I have a form with a custom simple mixins that implies that form's ids couldnt' be modified :/
So i have this :
<form t:type="form" t:id="formId" t:mixins="aMixins" t:zone="zoneID">
<t:errors/>
<input t:type="TextField"/>
<a t:type="LinkSubmit" t:id="linkId"/>
</form>
<t:zone t:id="zoneID">
Something....
</t:type>
When I use the zone form attribute, the validation errors aren't displayed, how can i make the validation errors displays errors without include the form into a zone ?
I can't include this form into a zone because when my mixin is initialized, it put some listeners on some DOM elements and when i submit my form, the form is reloaded (because of the zone) and reload the mixin too, which add some more listener on new DOM elements and after the submit an event is fired which is catched by corresponding listeners, but some of listeners are linked to unexistant elements and the js crash.
Thanks a lot for your reponses
1 .
I have a form with a custom simple mixins that implies that form's ids
couldnt' be modified
This is not implied. Maybe, it's your requirement?
If not then to plug in your mixin into ajax rendering you need to make the mixin a bit more flexible.
In YourMixin class:
#InjectContainer
private ClientElement element;
void afterRender() {
String elementId = element.getClientId();
JSONObject spec = new JSONObject();
spec.put("elementId", elementId);
jsSupport.addScript("new MixinHandler(%s)", spec.toString());
}
This is just a hint, take a look at Autocomplete implementation (class, javascript) for a complete sample.
2 .
When I use the zone form attribute, the validation isn't working
This sounds doubtful.. I guess validation errors are not visible because you do not update the form itself and its <t:errors/> tag.
This can be verified if you set break points into FAILURE and SUCCESS event handlers of the form in your page (see org.apache.tapestry5.EventConstants).

C# - Get textbox value and send to a javascript function

I have a simple form with three textboxes and a <canvas> on the same page and I have to validate these three fields and then get the values (if validated) sent to a javascript function to draw a picture and some text inside the <canvas> element. The form and textboxes wouldn't have to disappear after the values were submitted because the user could try out different results with different values. I've done other forms before but never tried using Ajax. I know I could use a client-side validation and get the textbox values with jQuery but I have more server-side code running that would make use of these three values. How can I do this?
in your controller, create a method to handle the results. I assume that this is for logging only, and does not need to actually return data.
public useResults(string value1, string value2)
{
// ... Do something with the results
return Json(true);
}
In your view, work out a way to construct the url to the above action. Perhaps in a hidden field;
#Html.Hidden("useResultsUrl", Url.Action("useResults", "controllerName"))
Then in your javascript, attach a click event to the button, as you probably have already (to trigger your javascript task) and add in an ajax call.
Note that the following uses JQuery, but you could use microsoft AJAX if you preferred;
$(function () {
$("#button").click(function() {
$.ajax({
url: $("input[name='useResultsUrl']").val(), // Get the url from the hidden field
type: "POST",
dataType: "JSON",
data: $("input[type='text']").serialize() // Get the value of the text inputs and serialise them.
});
});
// ... do other stuff
});
Your View can make an ajax call to the server using JQuery - either using JQuery.post
or JQuery.ajax - you give the Url of the controller action to the JQuery method, and it will handle the AJAX call for you.
Then, in your controller action, you return a JsonResult - which serialize the data for you into JSON format:
e.g. return Json( model );
Finally, implement a success function in the JQuery Ajax call in your view - this wil have the data returned by the controller available for you to do whatever you want with.

jQuery - submit form via AJAX and put results page into a div...?

I'm using jQuery Form (http://jquery.malsup.com/form/) to get send data to a form - is there a way I can then, without refresh, put the results page that's generated by the form into a div on the page?
Any advice appreciated!
I would suggest not using that form plugin - it was made back in the days before there was an easy way to serialize form data using jQuery, and serves no real purpose any more. I would suggest something like this:
$("form").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$("#someDiv").html(data);
});
return false; // prevent normal submit
});
If you insist on using jQuery Form Plugin - which is NOT recommended -, you can set the target option to a selector of the element(s) you would like to fill up:
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function(data) {
alert('Thanks for your comment!');
}
};
Take a look at http://jquery.malsup.com/form/#options-object for more info.
To prevent refresh, just make sure the form's onsubmit event returns false:
<form method="post" onsubmit="return false">