-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e4377d7
commit 2c36b86
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |