jetformbuilder
/
modules
/
blocks-v2
/
phone-field
/
assets
/
src
/
frontend
/
restrictions
/
PhoneRestriction.js
jetformbuilder
/
modules
/
blocks-v2
/
phone-field
/
assets
/
src
/
frontend
/
restrictions
Last commit date
PhoneRestriction.js
4 months ago
PhoneRestriction.js
69 lines
| 1 | let { |
| 2 | AdvancedRestriction, |
| 3 | Restriction, |
| 4 | } = window.JetFormBuilderAbstract || {}; |
| 5 | |
| 6 | // Fallback if AdvancedRestriction is not available |
| 7 | AdvancedRestriction = AdvancedRestriction || Restriction; |
| 8 | |
| 9 | /** |
| 10 | * Phone Number Validation Restriction |
| 11 | */ |
| 12 | function PhoneRestriction() { |
| 13 | AdvancedRestriction.call( this ); |
| 14 | |
| 15 | this.type = 'phone_validation'; |
| 16 | } |
| 17 | |
| 18 | PhoneRestriction.prototype = Object.create( AdvancedRestriction.prototype ); |
| 19 | |
| 20 | /** |
| 21 | * Only apply this restriction if field is a phone field |
| 22 | */ |
| 23 | PhoneRestriction.prototype.isSupported = function ( node ) { |
| 24 | const isPhoneField = node.classList.contains( 'phone-field' ); |
| 25 | |
| 26 | return isPhoneField; |
| 27 | }; |
| 28 | |
| 29 | /** |
| 30 | * Validate phone number using intl-tel-input |
| 31 | */ |
| 32 | PhoneRestriction.prototype.validate = function () { |
| 33 | const input = this.reporting.input; |
| 34 | const wrapper = input.getWrapperNode(); |
| 35 | const intlInput = wrapper?.querySelector('input.phone-field-intl'); |
| 36 | |
| 37 | // If itiInstance is not ready yet, skip validation (return true) |
| 38 | if ( ! input.itiInstance ) { |
| 39 | return true; |
| 40 | } |
| 41 | |
| 42 | // If intl input field is empty, let required restriction handle it |
| 43 | if ( ! intlInput || ! intlInput.value.trim() ) { |
| 44 | return true; |
| 45 | } |
| 46 | |
| 47 | // Validate using intl-tel-input |
| 48 | const isValid = input.itiInstance.isValidNumber(); |
| 49 | |
| 50 | return isValid; |
| 51 | }; |
| 52 | |
| 53 | /** |
| 54 | * Return validation error message |
| 55 | */ |
| 56 | PhoneRestriction.prototype.getRawMessage = function () { |
| 57 | // Try to get custom message from field configuration |
| 58 | const customMessage = this.getMessageBySlug?.( 'phone_invalid' ); |
| 59 | |
| 60 | if ( customMessage ) { |
| 61 | return customMessage; |
| 62 | } |
| 63 | |
| 64 | // Default message |
| 65 | return 'Please enter a valid phone number'; |
| 66 | }; |
| 67 | |
| 68 | export default PhoneRestriction; |
| 69 |