Custom field type validation in field type definition class Scenario: I created custom field type and need to add my own custom constraint/validation prior to saving.

Problem: failed to add custom constraint plugin so I implemented the function in 

public function preSave() {
$return = $this-&gt;custom_check($this-&gt;value, $this-&gt;getSetting('check_options'));
if(!$return[0]){
  drupal_set_message($return[1]-&gt;__toString(), 'error');
  $url = \Drupal::service('path.current')-&gt;getPath();
  $response = new RedirectResponse($url);
  $response-&gt;send();
  exit;
}
}

function custom_check($value, $check_options){
//checking goes here
}


I user drupal_set_message() and RedirectResponse as I couldn't get the $form or $formState of the node/%nid/edit to set the error at field and dor form rebuid.

I know that solution is not the best practice and I have to create my own constraints and validation but I spent time with no luck to work and I didn't found a working example that suits my case escpicially I need to validate based on field settings so I have to pass two parameters value and setting.

Please help getting the current form array and formstate in presave to rebuild instead of redirect. or show me how to write simple constraint that takes parameters and how to add it to my custom defined field type.

Thanks in advance.
Form validation checks the user input before it gets submitted. The submitted values don't necessarily go into the database, they can be used for other things. Presave can check values before they are stored in the database. The values don't need to come from a form, they can be generated by other code. So those two things are not connected.

If you want to validate a form, you have to use form validation. Presave doesn't know about forms. It is no problem to double check in presave, then you prevent wrong values to enter into the database from any code. But if you want to give the user a feedback in the form, use form validation. In presave you can only throw an exception after submit.