How to programmatically add a regex validator to a field?

Vote:
 

Hello,

I have a tool on a site I am working on that creates forms based on an existing page. One thing I am struggling with is how to programmatically add a regex validation to a text area. The following code works but it is hacky:

var maxChars = 1600;
var maxCharsRegex = $"^\\w{{1,{maxChars}}}$";

var regexValidator = new RegularExpressionValidator();
//this is how you are supposed to set the regex, however the following "ToRawString" command isn't working
//regexValidator.Initialize(maxCharsRegex);

//hack to add regex, see above comment
var validationStr = _validationService.ToRawString(regexValidator) + maxCharsRegex;
var validationMessage = new ValidatorMessage()
{
	Message = $"This has a character limit of {maxChars}.",
	Validator = typeof(RegularExpressionValidator).FullName
};

var requirementInput = CreateInput<TextareaElementBlock>($"text area name", formFolderRef, true,
	default, (input) =>
		{
			input.Validators = validationStr;
			input.ValidatorMessages = new List<ValidatorMessage> { validationMessage };
		});

The problem I'm having is with _validationService.ToRawString(...), it should produce the string: "EPiServer.Forms.Implementation.Validation.RegularExpressionValidator###^\w{1,10}$" but instead it creates the string "EPiServer.Forms.Implementation.Validation.RegularExpressionValidator###EPiServer.Forms.Core.Validation.Internal.RegularExpressionValidationModel" which is why I append my regex string manually.

Is there a more kosher way to do this?

#305849
Jul 28, 2023 18:16
Vote:
 

Hi Zach

From what you describe it seems ToRawString might have a bug in serializing validator models. Cause it looks like the Editor UI can properly serialize it, but the API cannot (using the default ToString() method). You might want to submit a bug report to Support.

#305921
Jul 30, 2023 19:26
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.