Question T10506
Visible to All Users

Is it possible to add validation for custom added property?

created 2 years ago (modified 2 years ago)

Hey,

we have a requirement , we need an image url property for survey, but wondering how to add a validation to check if the input is a valid image url like adding regular expression?
I have created an example here :
https://plnkr.co/edit/g40msrI32GZr0myc
I tried this, but seems like adding validation here is not working

Code
Survey.Serializer.addProperty("survey",  {        name"imageURL:text",        displayName: "imageURL",       category:"general",       validators: [              {                type: "regex",                text: LocalizedStrings.CorrectURL,                regex: "[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)"              }            ]      })

can you help, thanks

Answers approved by surveyjs Support

created 2 years ago (modified 2 years ago)

Hello Lei,
We suggest that you set the type of the imageURL property to a custom type (let's call it url). Next, register a Property Grid editor for this custom url type in the PropertyGridEditorCollection. Finally, subscribe to the creator.onPropertyValidationCustomError event and check whether the custom property value (options.value) is valid. Please test this example:

JavaScript
Survey.Serializer.addProperty('survey', { name: 'imageURL:url', displayName: 'imageURL', category: 'general', }); SurveyCreator.PropertyGridEditorCollection.register({ fit: function (prop) { return prop.type === 'url'; }, getJSON: function (obj, prop, options) { return { type: 'comment', textUpdateMode: 'onBlur' }; }, }); var creator = new SurveyCreator.SurveyCreator(options); creator.onPropertyValidationCustomError.add((sender, options) => { //Need to check url if (options.propertyName.indexOf('URL') > -1 && !!options.value) { const valid = /^(ftp|http|https):\/\/[^ "]+$/.test(options.value); if (!valid) { options.error = 'Please enter a valid URL'; } } });

See also: Property Grid Customization.

Feel free to contact us if you have any questions or require further assistance.

    Comments (1)

      For the record: we decided to enhance our library regarding this scenario and introduce an event to validate properties of custom types with ease. For more information, follow this thread: Add validateValue function into PropertyEditor inteface.