Create record in API but let Knack do the validation

As Knack form validation rules (as set in the builder at the form properties stage) work quite well, it is nice to be able to just use those inside the API. Through this, it's also possible to later change form validation rules very easily without need for additional coding.

Here is an example for a record create form where field1 is a connection and field 2 and 3 are both text/strings. It will enforce the form validation rules for the chosen view. In the case that validation fails, it will display an alertbox with the same text that Knack usually puts in a red box at the top of the form when validation fails; this text can be easily customised in the builder.


var myField1 = "57e7f95e28f539891fea014a"; //knack record ID, as string
var myField2 = "hello"; //string
var myField3 = $("#field_38").val(); //text field, converted to string I believe

var dataToPost = ""
dataToPost = {
field_1: myField1,
field_2: myField2,
field_3: myField3
};

console.log("Data to post:")
console.log(dataToPost);

// api
var api_url = 'https://api.knack.com/v1/scenes/scene_XX/views/view_XX/records'

$.ajax({
url: api_url
, type: "POST"
, headers: {
'X-Knack-Application-Id': '56fb8b0fad25a3be79b5053b'
, "Authorization": Knack.getUserToken();
, "content-type": "application/x-www-form-urlencoded"
}
, data: dataToPost
, success: function(response) {
console.log("Record added")
console.log(response);
}
, error: function (request, status, error) {
var myResponse = JSON.parse(request.responseText)
console.log(request);
alert(myResponse.errors["0"].message); //display an alert box showing knack's returned "validation failed" text, as set for the form in the builder
console.log(status);
}

});


}

Hey that's neat Anton - thanks for sharing.

(The main discovery here is that we can send data in format "application/x-www-form-urlencoded" rather than as json. This seems to be closer to simulating how the form and knack back-end interact, rather than trying to work directly with the back end)