Skip to content

Commit

Permalink
NEW Create PhoneField
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Sep 26, 2023
1 parent e4377d7 commit 2c36b86
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/Form/PhoneField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace SilverStripe\LinkField\Form;

use SilverStripe\Forms\TextField;
use SilverStripe\Forms\Validator;

/**
* Text input field with validation for correct email format according to RFC 2822.
*/
class PhoneField extends TextField
{
/**
* This needs to be not surronded by regex delimiters so that it works on the frontend
*/
private const RX = '^[()\- 0-9]+$';

/**
* This is used for the <input> element type="tel" attribute
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel
*/
protected $inputType = 'tel';

/**
* This is added as a classname to the <input> element
*/
public function Type()
{
return 'phone text';
}

/**
* @param Validator $validator
*
* @return string
*/
public function validate($validator)
{
$result = true;
$this->value = trim($this->value ?? '');
if ($this->value && !preg_match('#' . self::RX . '#', $this->value)) {
$validator->validationError(
$this->name,
_t(__CLASS__ . '.VALIDATION', 'Please entire a valid phone number'),
'validation'
);
$result = false;
}
return $this->extendValidationResult($result, $validator);
}

/**
* This is passed to the frontent via FormField::getSchemaValidation()
* and used in Validator.js
*/
public function getSchemaValidation()
{
$rules = parent::getSchemaValidation();
$rules['regex'] = ['pattern' => self::RX];
return $rules;
}
}

0 comments on commit 2c36b86

Please sign in to comment.