# Создание и регистрация кастомных типов переменной и кастомные валидаторы

**URL:** <https://camunda.reunico.com/t/sozdanie-i-registracziya-kastomnyh-tipov-peremennoj-i-kastomnye-validatory/84>\
**Category:** Camunda Modeler и BPMN\
**Created:** [28.Май.2021 19:04:42 UTC](https://camunda.reunico.com/t/sozdanie-i-registracziya-kastomnyh-tipov-peremennoj-i-kastomnye-validatory/84 "2021-05-28T19:04:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![abobrov](https://camunda.reunico.com/letter_avatar_proxy/v4/letter/a/db5fbb/32.png) [@abobrov](https://camunda.reunico.com/u/abobrov)\
**Post date:** [28.Май.2021 19:04:42 UTC](https://camunda.reunico.com/t/sozdanie-i-registracziya-kastomnyh-tipov-peremennoj-i-kastomnye-validatory/84/1 "2021-05-28T19:04:42Z")

</div>

Коллеги, всем привет!

Появилась необходимость проверять MIME-Type у приложенных файлов в пользовательской задаче.

Используется camunda версии 7.13.0

Как выяснилось при создании формы в Camunda Modeler типа переменной file нет. Поэтому реализовал собственный тип как описано ниже:

> **[Custom Form Field Type for file upload](https://forum.camunda.org/t/custom-form-field-type-for-file-upload/6704/2)**
>
> Answering my own question here in case in case it’s useful for anyone else in the future: I followed the instructions here to register a custom form type FileFormFieldType. And then my implementation of the class FileFormFieldType looks something...

и зарегистрировал его в конфигурацинном файле камунды:

```
@Override
    public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
        if (processEngineConfiguration.getCustomFormTypes() == null) {
            processEngineConfiguration.setCustomFormTypes(new ArrayList<AbstractFormFieldType>());
        }

        List<AbstractFormFieldType> formTypes = processEngineConfiguration.getCustomFormTypes();
        formTypes.add(new FileFormFieldType());
    }

```

Далее создал кастомный валидатор и сделал обращение к нему из формы при помощи вызова бина как в примере ниже:  
[В конце главы про generated-task-forms](https://docs.camunda.org/manual/7.13/user-guide/task-forms/#generated-task-forms)

Данный валидатор вызывается при сабмите формы как и положено. Основная задача его проверить, что приложенный файл имеет нужный MIME-type. Но данный файл поступает в метод как inputObject и является экземпляром ByteArrayInputStream. Получить метаданные из variableScope - не получается, т.к. данная переменная еще не находится в скоупе переменных процесса.

Подскажите, где что делаю не так или, может, другой рабочий подход. Но хотелось бы разобраться как делать через кастомные валидаторы 🙂

---

<div class="post-metadata">

**Author:** ![Mstislav](https://camunda.reunico.com/user_avatar/camunda.reunico.com/mstislav/32/102_2.png) [@Mstislav](https://camunda.reunico.com/u/Mstislav)\
**Post date:** [07.Июнь.2021 19:10:21 UTC](https://camunda.reunico.com/t/sozdanie-i-registracziya-kastomnyh-tipov-peremennoj-i-kastomnye-validatory/84/2 "2021-06-07T19:10:21Z")

</div>

Если исходить из утверждения, что имя поля формы = имя переменной процесса, то можно реализовать валидатор через TypedVariable:

```auto
public class CustomValidator implements FormFieldValidator {

    public boolean validate(Object submittedValue, FormFieldValidatorContext validatorContext) {

        // ... do some custom validation of the submittedValue

        // get access to the current execution
        DelegateExecution e = validatorContext.getExecution();

        // get access to all form fields submitted in the form submit
        Map<String,Object> completeSubmit = validatorContext.getSubmittedValues();

        // Получить TypedVariable (это обертка над переменной процесса, содержащая в себе метаданные:
        // имя файла, mime-type, способ сериализации, класс объекта и ид
        FileValue fileValue = validatorContext.getVariableScope().getVariableTyped("file");

        InputStream is = fileValue.getValue();
        String fileName = fileValue.getFilename();
        String encoding = fileValue.getEncoding();
        String mimeType = fileValue.getMimeType();
        
        // Только фоточки
        return mimeType.equals(MimeTypes.JPG);

    }

}

```
