Yup, you read it right. Validations can be added to the properties in the web part property pane of an SPFx webpart. The validation function can be Synchronous as well as Asynchronous.
This means that we can immediately determine whether a property is valid or we can make an HTTP request (e.g. to SharePoint) and then determine if a property is valid depending on the response.
In the following code, I have added a validation to the title property to make sure that it is not the same as the SharePoint site title. Also, I have added a validation to the description property making sure that it is not less than 10 characters.
The code is pretty straightforward. This code should be placed inside your Web part class:
As you can see from the code, the _validateTitleAsync function fires when the title property is edited. It makes a GET request to SharePoint to get the title of the web:
The code for this post is located here: https://github.com/vman/SPFx-Web-part-property-validator
The complete Web part class with the property pane editor is here:
While working on this post, I have discovered two possible issues with the way property pane validations currently work in the SharePoint Framework. I have posted them here if you are interested:
1) Rename IPropertyPaneTextFieldProps.onGetErrorMessage to IPropertyPaneTextFieldProps.GetValidationMessage
2) When property pane is in Non-Reactive mode, the validation function should only fire when clicked on "Apply"
Thanks for reading!