Question T10161
Visible to All Users

add valid json check

created 2 years ago

Hey,

We have a question for survey js library.
we have a suvey json like this :

Code
export const CustomJson = (LocalizedStrings: any) => {   return {     pages: [       {         name: "page1",         elements: [           {             type: "comment",             name: "AppleMessagesforBusinessJSON",             title: LocalizedStrings.AppleMessagesforBusinessJSON,             isRequired: true,             placeHolder: LocalizedStrings.EnterJSON           }         ]       }     ]   }; };

we want to make sure user input VALID JSON in the comment question. is there a way to do that? For example function call?
And if not, how can we highlight the question during complete, do we have a function similar like survey.selectElement(questions[0]);

Answers approved by surveyjs Support

created 2 years ago

Hello Lei,
You can register a custom function and then use it in expression validator.
Here is the code and the working example.

JavaScript
function isValidJSON(params{   if (params.length == 0 || !params[0]) return false;   try {     JSON.parse(params[0]);   } catch (e) {     return false;   }   return true; } // Register the function for use in SurveyJS expressions Survey.FunctionFactory.Instance.register('isValidJSON', isValidJSON); const json = {   elements: [     {       type'comment',       name'memo',       isRequiredtrue,       title'Please enter a valid JSON:',       validators: [         {           type'expression',           text"Please enter a valid JSON",           expression'isValidJSON({memo})',         },       ],     },   ], };

Thank you,
Andrew
SurveyJS Team
If you like our products, please take a moment to share your experience with our company by contributing a short review for SurveyJS page at g2.com or at Trustpilot.com.
As we’re building our business, every review helps build credibility for future customers and your feedback would be greatly appreciated.