Survey.StylesManager.applyTheme("default");
//Function that returns the value on callback async
function isCountryExist(params) {
if (params.length < 1) return false;
var countryName = params[0];
//If the question is empty then do nothing
if (!countryName) {
//It doesn't matter what the function returns. The library is wating for this.returnResult(resultValue) callback
this.returnResult(false);
return false;
}
var self = this;
//call the ajax method
$.ajax({
url: "https://restcountries.eu/rest/v2/all"
}).then(function (data) {
var found = false;
var countries = data;
for (var i = 0; i < countries.length; i++) {
if (countries[i].name == countryName) {
found = true;
break;
}
}
// return the value into the library. Library is waiting for this callback
self.returnResult(found);
});
//May return any value. The library will ignore it.
return false;
}
// It is important to tell the library that the function is async, the last parameter
// and you will return the value on this.returnResult callback
Survey.FunctionFactory.Instance.register("isCountryExist", isCountryExist, true);
/*
If you do not need to support es5 (IE), then you may use async/await operators
async function isCountryExist(params) {
if (params.length < 1) return false;
var countryName = params[0];
if (!countryName) {
this.returnResult(false);
return false;
}
var self = this;
var res = await $.ajax({
url: "https://restcountries.eu/rest/v2/all"
}).then(function(data) {
var found = false;
var countries = data;
for (var i = 0; i < countries.length; i++) {
if (countries[i].name == countryName) {
found = true;
break;
}
}
self.returnResult(found);
});
return false;
}
*/
var json = {
elements: [
{
type: "text",
name: "country",
title: "Type a country:",
validators: [
{
type: "expression",
expression: "isCountryExist({country}) = true",
text: "Please type the country correctly"
}
]
},
{
type: "comment",
name: "aboutCountry",
title: "Please tell us about country: '{country}'",
visibleIf: "isCountryExist({country}) = true"
}
]
};
window.survey = new Survey.Model(json);
survey.onComplete.add(function(result) {
document.querySelector('#surveyResult').textContent =
"Result JSON:\n" + JSON.stringify(result.data, null, 3);
});
survey.render("surveyElement");
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using asynchron functions in expression validator, Knockoutjs Survey Library Example</title>
<meta name="viewport" content="width=device-width" />
<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/knockout@3.5.1/build/output/knockout-latest.js"></script>
<script src="/DevBuilds/survey-knockout/survey.ko.min.js"></script>
<link href="/DevBuilds/survey-knockout/survey.min.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="surveyElement" style="display:inline-block;width:100%;">
</div>
<div id="surveyResult"></div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>