There may arise situations where your custom EPiServer Forms field blocks make no sense without your custom validation code being applied as the website visitor submits the form. In these cases it may be useful to help the web editor by preventing the need to tick the correct validation checkbox in the form element block. Creds to my collegue Christer Bermar for his work on this one.
Forcing a validatorn onto an EPiServer Forms field block
The method is rather straight forward. All you really have to do is override the Validators property that you get from inheriting from EPiServer‘s TextElementBlock class. You will need to append your validator’s fully qualified name (that’s the namespace plus your class name) to the separated string provided by EPiServer.
SomeLuhnTextBlock.cs
[ContentType( GUID = "450FDCDE-A9D4-4A66-A060-750C150E923B", DisplayName = "Some Luhn Text Block")] [AvailableValidatorTypes(Include = new[]{ typeof(RequiredValidator )})] public class SomeLuhnTextBlock : TextboxElementBlock { public override string Validators { get { var luhnValidator = typeof(LuhnValidator).FullName; var validators = this.GetPropertyValue(content => content.Validators); if (string.IsNullOrEmpty(validators)) { return luhnValidator; } return string.Concat(validators, EPiServer.Forms.Constants.RecordSeparator, luhnValidator); } set { this.SetPropertyValue(content => content.Validators, value); } } }
Note that there is no need to keep your validator in the attribute AvailableValidatorTypes, and should you want to, you could also override your validator’s AvailableInEditView property as below.
Somewhere in LuhnValidator.cs
public override bool AvailableInEditView { get { return false; } }
Cheers Mathias :)