Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

Custom validation for phone-number using class-validator package

import { ClassConstructor } from 'class-transformer';
import {
    ValidationOptions,
    registerDecorator,
    ValidationArguments,
    ValidatorConstraintInterface,
    ValidatorConstraint,
} from 'class-validator';
import { PhoneNumberUtil } from 'google-libphonenumber';
import * as iso from 'i18n-iso-countries';

// phone-number validator
export const IsValidNumberOf = <T>(
    type: ClassConstructor<T>,
    property: (o: T) => any,
    validationOptions?: ValidationOptions,
) => {
    return (object: any, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [property],
            validator: IsValidNumberOfConstraint,
        });
    };
};

@ValidatorConstraint({ name: 'IsValidNumberOf', async: true })
export class IsValidNumberOfConstraint implements ValidatorConstraintInterface {
    validate(value: any, args: ValidationArguments) {
        const util = PhoneNumberUtil.getInstance();

        const [fn] = args.constraints;
        // get the value of the country Field
        const countryCode = fn(args.object);
        // check if the country is valid even though it is checked at class level 
        const isValidISOCode = iso.isValid(countryCode);
        if (!isValidISOCode) {
            return false;
        }

        // Checks if the value (number) belongs in the extracted countryCode 
        const formattedPhoneNumber = util.parse(value, countryCode);
        const isValidPhoneNumber = util.isValidNumberForRegion(formattedPhoneNumber, countryCode);
        if (!isValidPhoneNumber) {
            return false;
        }

        return true;
    }

    defaultMessage(args: ValidationArguments) {
        // const [constraintProperty]: (() => any)[] = args.constraints;
        return `${args.property} must be a valid phone-number in the specified country`;
    }
}

// user
import { IsISO31661Alpha2, IsNotEmpty } from 'class-validator';
import { IsValidNumberOf } from '../../validators/is-valid-number-of.validator';
import { IPhoneNumber } from '../../interfaces/shared/phone-number.interface';

export class PhoneNumberDTO implements IPhoneNumber {
    @IsValidNumberOf(PhoneNumberDTO, (o: { country: any; }) => o.country)
    number: string;

    @IsNotEmpty()
    @IsISO31661Alpha2()
    country: string;
}
Comment

PREVIOUS NEXT
Code Example
Typescript :: update a xml document if its not empty on c# 
Typescript :: validation minlength angular 
Typescript :: create CSS class in directive angular 
Typescript :: links a otros components angular 
Typescript :: can ts object be strongly typed? 
Typescript :: how to Write a program that accepts three decimal numbers as input and outputs their sum on python 
Typescript :: typescript dynamic dict 
Typescript :: react inherit html input props 
Typescript :: remove showing results woocommerce shortcode 
Typescript :: ipywidgets hide widget 
Typescript :: nginx rest api caching 
Typescript :: typescript one of array 
Typescript :: list of objects where linq 
Typescript :: display entry count for specific column using value_counts spyder. 
Typescript :: file reader with promise 
Typescript :: typescript interface to http params 
Typescript :: react fc typescript 
Typescript :: int sum. 
Typescript :: Push Type Typescript 
Typescript :: how to pring events in pygame 
Typescript :: nullish coalescing typescript 
Typescript :: why do we write unit tests in programming 
Typescript :: inheritance problem in Dart 
Typescript :: Cave Generator 
Typescript :: Display Popular Posts laravel 
Typescript :: convert epoch to normal date | stripe | epoch 
Typescript :: detect incomming bullet from socket 
Typescript :: How to loop the jquery formData key object in jqueyr 
Typescript :: typescript abstract static method 
Typescript :: input adresse ville automatique 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =