You can do it with two ways
- With Webform Custom Handlers.
- With custom js.
I prefer you to go with the 1st approach I mentioned above. How to create and work with webform custom handlers is documented well on drupal.org's webform document. Attaching here for quick reference.
namespace Drupal\mys_module\Plugin\WebformHandler;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\Component\Utility\Html;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Webform validate handler.
*
* @WebformHandler(
* id = "my_module_custom_validator",
* label = @Translation("Alter form to validate it"),
* category = @Translation("Settings"),
* description = @Translation("Form alter to validate it."),
* cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
* )
*/
class CustomValidatorWebformHandler extends WebformHandlerBase {
use StringTranslationTrait;
//We will overwrite the method validateForm, inherit from WebformHandlerBase.
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
$this->validatePhone($form_state);
}
//We will define a new method to validate for example the phone.
/**
* Validate phone.
*/
private function validatePhone(FormStateInterface $formState) {
$value = !empty($formState->getValue('phone')) ? Html::escape($formState->getValue('phone')) : NULL;
// Skip empty unique fields or arrays (aka #multiple).
if (empty($value) || is_array($value)) {
return;
}
if ($value > 9) {
$formState->setErrorByName('phone', $this->t('Phone not valid.'));
}
else {
$formState->setValue('phone', $value);
}
}
}
Enable it for your webform: The route to administer the handlers of a Webform is /admin/structure/webform/manage/[your_webform_name]/handlers
The second way is to add javascript in assets section of the webform:
Route is: /admin/structure/webform/manage/[webform]/settings/assets
In the case of jQuery, I suggest instead of removing the required
try adding it. As the property is configured in the webform element setting.