CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cleave-js

JavaScript library for formatting input text content when you are typing

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

angular-integration.mddocs/

Angular Integration

Complete API reference for using Cleave.js with AngularJS applications through the provided directive with ngModel integration and two-way data binding.

Capabilities

Angular Directive

The Cleave AngularJS directive provides seamless integration with Angular forms and ngModel for two-way data binding.

/**
 * Cleave AngularJS directive
 * Requires ngModel and integrates with Angular form validation 
 */
angular.module('cleave.js', [])
  .directive('cleave', function () {
    return {
      restrict: 'A', // Attribute directive
      require: 'ngModel', // Requires ngModel controller
      scope: {
        cleave: '&', // Function expression returning options object
        onInit: '&?', // Optional initialization callback
        onValueChange: '&?' // Optional value change callback
      }
      // ... internal implementation
    };
  });

/**
 * Directive usage pattern
 */
interface CleaveAngularDirectiveUsage {
  cleave: () => CleaveOptions; // Function returning configuration options
  onInit?: (instance: CleaveInstance) => void; // Instance initialization callback
  onValueChange?: (formattedValue: string) => void; // Formatted value change callback
}

interface CleaveInstance {
  setRawValue(value: string): void;
  getRawValue(): string;
  getFormattedValue(): string;
  getISOFormatDate(): string;
  getISOFormatTime(): string;
  destroy(): void;
  element: HTMLInputElement;
}

Basic Angular Usage

Usage Examples:

<!-- Include the cleave.js module -->
<script>
angular.module('myApp', ['cleave.js']);
</script>

<!-- Basic usage with ngModel -->
<input 
  ng-model="creditCardNumber" 
  cleave="getCreditCardOptions()"
  placeholder="Credit card number">

<!-- With callbacks -->
<input 
  ng-model="phoneNumber"
  cleave="getPhoneOptions()"
  on-init="onCleaveInit(instance)"
  on-value-change="onPhoneChange(value)"
  placeholder="Phone number">

<!-- Date input with validation -->
<input 
  ng-model="birthDate"
  cleave="getDateOptions()"
  required
  placeholder="Birth date">
// Controller implementation
angular.module('myApp').controller('MyController', function($scope) {
  // Model values (raw values)
  $scope.creditCardNumber = '';
  $scope.phoneNumber = '';
  $scope.birthDate = '';
  
  // Configuration functions
  $scope.getCreditCardOptions = function() {
    return {
      creditCard: true,
      onCreditCardTypeChanged: function(type) {
        $scope.cardType = type;
        $scope.$apply(); // Trigger digest cycle
      }
    };
  };

  $scope.getPhoneOptions = function() {
    return {
      phone: true,
      phoneRegionCode: 'US'
    };
  };

  $scope.getDateOptions = function() {
    return {
      date: true,
      datePattern: ['m', 'd', 'Y']
    };
  };

  // Callback functions
  $scope.onCleaveInit = function(instance) {
    console.log('Cleave initialized:', instance);
  };

  $scope.onPhoneChange = function(formattedValue) {
    console.log('Phone formatted value:', formattedValue);
  };
});

ngModel Integration

The directive automatically integrates with ngModel for two-way data binding.

/**
 * ngModel integration behavior
 * - Model receives raw unformatted values
 * - View displays formatted values  
 * - Formatters convert model to view
 * - Parsers convert view to model
 */
interface NgModelIntegration {
  // Model value (raw)
  $modelValue: string;
  
  // View value (formatted)  
  $viewValue: string;
  
  // Formatters: model -> view
  $formatters: Array<(value: string) => string>;
  
  // Parsers: view -> model
  $parsers: Array<(value: string) => string>;
}

Usage Examples:

<form name="paymentForm">
  <input 
    name="cardNumber"
    ng-model="payment.cardNumber"
    cleave="getCreditCardOptions()"
    required>
  
  <input
    name="amount" 
    ng-model="payment.amount"
    cleave="getCurrencyOptions()"
    required>
    
  <p>Raw card number: {{ payment.cardNumber }}</p>
  <p>Form valid: {{ paymentForm.$valid }}</p>
</form>
angular.module('myApp').controller('PaymentController', function($scope) {
  $scope.payment = {
    cardNumber: '', // Raw value stored in model
    amount: ''      // Raw numeric value
  };

  $scope.getCreditCardOptions = function() {
    return { creditCard: true };
  };

  $scope.getCurrencyOptions = function() {
    return {
      numeral: true,
      numeralDecimalScale: 2,
      prefix: '$'
    };
  };

  $scope.submitPayment = function() {
    if ($scope.paymentForm.$valid) {
      console.log('Submitting:', $scope.payment);
      // payment.cardNumber contains raw digits
      // payment.amount contains raw numeric value
    }
  };
});

Dynamic Configuration

Changing Cleave options based on scope variables.

/**
 * Dynamic configuration pattern using scope watchers
 * The directive automatically watches the cleave expression and recreates
 * the Cleave instance when options change
 */
interface DynamicConfiguration {
  // Scope watcher automatically detects option changes
  $watch: (expression: string, callback: Function, deep: boolean) => void;
}

Usage Examples:

<select ng-model="selectedCountry">
  <option value="US">United States</option>
  <option value="UK">United Kingdom</option>
  <option value="AU">Australia</option>
</select>

<input 
  ng-model="phoneNumber"
  cleave="getPhoneOptions()"
  placeholder="Phone number">
angular.module('myApp').controller('DynamicController', function($scope) {
  $scope.selectedCountry = 'US';
  $scope.phoneNumber = '';

  $scope.getPhoneOptions = function() {
    return {
      phone: true,
      phoneRegionCode: $scope.selectedCountry
    };
  };

  // The directive automatically watches getPhoneOptions() result
  // and recreates Cleave instance when selectedCountry changes
});

Form Validation Integration

Using Cleave with Angular form validation.

Usage Examples:

<form name="registrationForm" ng-submit="submitForm()">
  <div>
    <label>Credit Card:</label>
    <input 
      name="creditCard"
      ng-model="user.creditCard"
      cleave="getCreditCardOptions()"
      required
      ng-minlength="13"
      ng-maxlength="19">
    
    <div ng-show="registrationForm.creditCard.$invalid && registrationForm.creditCard.$touched">
      <span ng-show="registrationForm.creditCard.$error.required">Credit card is required</span>
      <span ng-show="registrationForm.creditCard.$error.minlength">Credit card too short</span>
    </div>
  </div>

  <div>
    <label>Phone:</label>
    <input 
      name="phone"
      ng-model="user.phone"
      cleave="getPhoneOptions()"
      required
      ng-pattern="/^\d{10}$/">
      
    <div ng-show="registrationForm.phone.$invalid && registrationForm.phone.$touched">
      <span ng-show="registrationForm.phone.$error.required">Phone is required</span>
      <span ng-show="registrationForm.phone.$error.pattern">Invalid phone format</span>
    </div>
  </div>

  <button type="submit" ng-disabled="registrationForm.$invalid">
    Submit
  </button>
</form>
angular.module('myApp').controller('ValidationController', function($scope) {
  $scope.user = {
    creditCard: '',
    phone: ''
  };

  $scope.getCreditCardOptions = function() {
    return { creditCard: true };
  };

  $scope.getPhoneOptions = function() {
    return {
      phone: true,
      phoneRegionCode: 'US'
    };
  };

  $scope.submitForm = function() {
    if ($scope.registrationForm.$valid) {
      console.log('Valid form data:', $scope.user);
      // user.creditCard contains raw card digits
      // user.phone contains raw phone digits
    }
  };
});

Custom Validation

Adding custom validation logic with Cleave formatting.

Usage Examples:

<input 
  name="customField"
  ng-model="customValue"
  cleave="getCustomOptions()"
  custom-validator
  required>
angular.module('myApp')
  .directive('customValidator', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$validators.custom = function(modelValue, viewValue) {
          // Custom validation logic using raw value
          const value = modelValue || viewValue;
          return value && value.length >= 5;
        };
      }
    };
  })

  .controller('CustomValidationController', function($scope) {
    $scope.customValue = '';

    $scope.getCustomOptions = function() {
      return {
        blocks: [4, 4, 4],
        delimiter: '-',
        uppercase: true
      };
    };
  });

Multiple Instances

Managing multiple Cleave instances in the same controller.

Usage Examples:

<div ng-controller="MultipleInstancesController">
  <input 
    ng-model="form.cardNumber"
    cleave="cardOptions"
    on-init="onCardInit(instance)">
    
  <input 
    ng-model="form.expiryDate"
    cleave="dateOptions"
    on-init="onDateInit(instance)">
    
  <input 
    ng-model="form.cvv"
    cleave="cvvOptions"
    on-init="onCvvInit(instance)">
    
  <button ng-click="clearAllFields()">Clear All</button>
  <button ng-click="fillTestData()">Fill Test Data</button>
</div>
angular.module('myApp').controller('MultipleInstancesController', function($scope) {
  $scope.form = {
    cardNumber: '',
    expiryDate: '',
    cvv: ''
  };

  // Store Cleave instances
  $scope.cleaveInstances = {};

  // Configuration objects
  $scope.cardOptions = { creditCard: true };
  $scope.dateOptions = { 
    blocks: [2, 2], 
    delimiter: '/',
    numericOnly: true 
  };
  $scope.cvvOptions = { 
    blocks: [4], 
    numericOnly: true 
  };

  // Instance callbacks
  $scope.onCardInit = function(instance) {
    $scope.cleaveInstances.card = instance;
  };

  $scope.onDateInit = function(instance) {
    $scope.cleaveInstances.date = instance;
  };

  $scope.onCvvInit = function(instance) {
    $scope.cleaveInstances.cvv = instance;
  };

  // Utility functions
  $scope.clearAllFields = function() {
    Object.values($scope.cleaveInstances).forEach(instance => {
      instance.setRawValue('');
    });
  };

  $scope.fillTestData = function() {
    $scope.cleaveInstances.card.setRawValue('4111111111111111');
    $scope.cleaveInstances.date.setRawValue('1225');
    $scope.cleaveInstances.cvv.setRawValue('123');
  };
});

Lifecycle Management

Proper cleanup and lifecycle management with Angular.

/**
 * Lifecycle management
 * The directive automatically handles cleanup on scope destruction
 */
interface LifecycleManagement {
  // Automatic cleanup on scope destroy
  $on(event: '$destroy', callback: () => void): void;
  
  // Manual instance management if needed
  destroy(): void;
}

Usage Examples:

angular.module('myApp').controller('LifecycleController', function($scope) {
  $scope.cleaveInstance = null;

  $scope.onCleaveInit = function(instance) {
    $scope.cleaveInstance = instance;
    
    // Custom initialization logic
    console.log('Cleave initialized');
  };

  // Manual cleanup if needed (automatic cleanup is already handled)
  $scope.$on('$destroy', function() {
    if ($scope.cleaveInstance) {
      console.log('Cleaning up Cleave instance');
      // Additional cleanup if needed
    }
  });

  // Dynamic instance recreation
  $scope.recreateInstance = function() {
    if ($scope.cleaveInstance) {
      $scope.cleaveInstance.destroy();
    }
    // New instance will be created by directive
  };
});

Install with Tessl CLI

npx tessl i tessl/npm-cleave-js

docs

angular-integration.md

index.md

phone-formatting.md

react-integration.md

vanilla-javascript.md

tile.json