Try our conversational search powered by Generative AI!

Custom form elements: How to access model properties in validator

Vote:
 

I'm in the process of creating a numeric input custom form element, consisting of a view, a model inheriting from InputElementBlockBase, and a validator inheriting from ElementValidatorBase.

And I'm specifying limitations for the element in the model, for the editor to specify when adding the element.  But how can I access the model in the validator, to validate the submitted value against the property values in the model?

#316802
Feb 07, 2024 13:08
Vote:
 

You override the Validate method from ElementValidatorBase, where you have IElementValidatable interface as parameter.

public override bool? Validate(IElementValidatable targetElement)
{
    var submittedValue = targetElement.GetSubmittedValue() as string;

    //validate submittedValue.
}

after that you kan override BuildValidationModel method to build the model and pass the validation message you want.

public override IValidationModel BuildValidationModel(IElementValidatable targetElement)
{
    if (_model == null)
    {
        _model = base.BuildValidationModel(targetElement);
        _model.Message = _localizationService.GetString("/episerver/forms/validators/elementselfvalidator/unexpectedvalueisnotaccepted");
    }
    return _model;
}

You can also access the model when inherting ElementValidatorBase with "_model" property.

I hope this helps :-) 

#316803
Feb 07, 2024 14:02
Øystein - Feb 13, 2024 9:41
Thanks for the help. My validator and building the validation model worked fine, with hard-coded test limits. My problem was getting the values from the field model.
Vote:
 

In the Validate() method in your validator, you should be able to cast targetElement as your custom element type which should allow you to access the properties set on the element. For example:

public class TestValidator : ElementValidatorBase
{
    public override bool? Validate(IElementValidatable targetElement)
    {
        if (targetElement is MyCustomElementType myElement)
        {
            //add your validation here
            var submittedValue = targetElement.GetSubmittedValue() as string;
            return (submittedValue.Contains(myElement.submittedValueShouldntContainThisPropertyValue));
        }
        return true;
    }
}
#316804
Feb 07, 2024 14:19
Øystein - Feb 13, 2024 9:38
This was exactly what I was looking for. Worked perfectly. 💪
* 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.