0.1.0 • Published 7 years ago

@orchejs/validators v0.1.0

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

Orche Validators

Build Status Coverage Status


This library contains common validators that may be used in Orchejs projects. It doesn't mean that you cannot use it in other type of projects, by the way, it would be a good practice to use the same backend validators in frontend or mobile projects. For example, to use a validator in an Angular project, it would be necessary to create a directive calling one of the validators of @orche/validators.

This project is divided in two kinds of validators: Global and Local. The first one comprises common validators, which means, anything that are not from a specific country or region. Examples of global validators are email, not null and length checkers. Local validators are anything that belongs to a specific country like zip code, documents as ID cards and so on.

The idea here is to make a public repository that may grow with the community contribution. So if you need a validator that does not exists here, please open a PR and help us to improve it. For contributions, please check the contributions topic.


Topics

How to use it in Orchejs

How to install?

This library is already bundled in the Orchejs projects. So you actually don't need to install anything.

How to use it in @orche/rest

The validators can be used for endpoint parameters validation or to validate a property in a class that can be a resource.

Endpoint parameter validation

When creating a Route, it's possible to add a validation to the parameter.

@Route()
export class Students {
  @Get()
  getStudent(@QueryParam('name', { 
    validators: [{
      validator: NotNullValidator
    }]
  }) name: string) {
    // ... logic..
  }
}

In this example, the NotNullValidator will run before the endpoint logic execution. So if any validation error happens, it will not pass to the route execution and will send the response error. Pretty forward isn't it? The result is a clean code.

Property class validation

Besides validating a basic variable type, it is also possible to validate a property of an object. This is useful for insert or update where it is usually sent an object into the body of the HTTP request.

export class Student {
  _id: ObjectId;

  @Property({ 
    validators: [ {
      validator: NotNullValidator
    }]
  })
  _name: string;

  @Property({
    validators: [{
      validator: EmailValidator
    }]
  })
  _email: string;

  @Property({
    validators: [{
        validator: MinValidator,
        params: 2,
        message: 'Students must be at least 2 years old'
    }]
  })  
  _age: number;

  get name() {
    return this._name;
  }

  set name(name: string) {
    this._name = name;
  }

  // ...
}

@Route()
export class Students {
  @Post()
  createStudent(@BodyParam() student: Student) {
    // ... logic..
  }
}

In this example, when making a HTTP Post request to /students the endpoint will execute only if all validators of Student are met. Again, the result code will be a clean.

Global validators

Global validators comprise all validations that are common to everyone. The following list is bundled to this library:

ValidatorDescription
EmailValidatorPerforms email validation.
MaxLengthValidatorValidates if the length of a value, that can be a string or Array, is not higher than the maximum length.
MaxValidatorValidates if a value is not higher than a number.
MinLengthValidatorValidates if the length of a value, that can be a string or Array, is higher than the minimum length.
MinValidatorValidates if a value is higher than a number.
NotEmptyValidatorValidates if a value is not undefined, null and blank ''
NotNullValidatorValidates if a value is null or undefined.
PatternValidatorValidates if a value matches a regex.

Local validators

Local validators support regional validation rules as document validations, ID card, social security, zip code, phone numbers and so on. This regional or country specific validators are organized in a locale folder structure.

To correctly name the folder, the following language tags list must be considered. This list was extracted from Locale codes.

Important: The name must be in lowercase and separated by hyphen. Example: en-us.

LocaleLanguage tag
Afrikaansaf
Albaniansq
Amharicam
Arabic - Algeriaar-dz
Arabic - Bahrainar-bh
Arabic - Egyptar-eg
Arabic - Iraqar-iq
Arabic - Jordanar-jo
Arabic - Kuwaitar-kw
Arabic - Lebanonar-lb
Arabic - Libyaar-ly
Arabic - Moroccoar-ma
Arabic - Omanar-om
Arabic - Qatarar-qa
Arabic - Saudi Arabiaar-sa
Arabic - Syriaar-sy
Arabic - Tunisiaar-tn
Arabic - United Arab Emiratesar-ae
Arabic - Yemenar-ye
Armenianhy
Assameseas
Azeri - Cyrillicaz-az
Azeri - Latinaz-az
Basqueeu
Belarusianbe
Bengali - Bangladeshbn
Bengali - Indiabn
Bosnianbs
Bulgarianbg
Burmesemy
Catalanca
Chinese - Chinazh-cn
Chinese - Hong Kong SARzh-hk
Chinese - Macau SARzh-mo
Chinese - Singaporezh-sg
Chinese - Taiwanzh-tw
Croatianhr
Czechcs
Danishda
DivehiMaldivian
Dutch - Belgiumnl-be
Dutch - Netherlandsnl-nl
English - Australiaen-au
English - Belizeen-bz
English - Canadaen-ca
English - Caribbeanen-cb
English - Great Britainen-gb
English - Indiaen-in
English - Irelanden-ie
English - Jamaicaen-jm
English - New Zealanden-nz
English - Phillippinesen-ph
English - Southern Africaen-za
English - Trinidaden-tt
English - United Statesen-us
Estonianet
FYRO Macedoniamk
Faroesefo
Farsi - Persianfa
Finnishfi
French - Belgiumfr-be
French - Canadafr-ca
French - Francefr-fr
French - Luxembourgfr-lu
French - Switzerlandfr-ch
Gaelic - Irelandgd-ie
Gaelic - Scotlandgd
German - Austriade-at
German - Germanyde-de
German - Liechtensteinde-li
German - Luxembourgde-lu
German - Switzerlandde-ch
Greekel
Guarani - Paraguaygn
Gujaratigu
Hebrewhe
Hindihi
Hungarianhu
Icelandicis
Indonesianid
Italian - Italyit-it
Italian - Switzerlandit-ch
Japaneseja
Kannadakn
Kashmiriks
Kazakhkk
Khmerkm
Koreanko
Laolo
Latinla
Latvianlv
Lithuanianlt
Malay - Bruneims-bn
Malay - Malaysiams-my
Malayalamml
Maltesemt
Maorimi
Marathimr
Mongolianmn
Mongolianmn
Nepaline
Norwegian - Bokmlno-no
Norwegian - Nynorskno-no
Oriyaor
Polishpl
Portuguese - Brazilpt-br
Portuguese - Portugalpt-pt
Punjabipa
Raeto-Romancerm
Romanian - Moldovaro-mo
Romanian - Romaniaro
Russianru
Russian - Moldovaru-mo
Sanskritsa
Serbian - Cyrillicsr-sp
Serbian - Latinsr-sp
Setsuanatn
Sindhisd
Sinhalasi
Slovaksk
Sloveniansl
Somaliso
Sorbiansb
Spanish - Argentinaes-ar
Spanish - Boliviaes-bo
Spanish - Chilees-cl
Spanish - Colombiaes-co
Spanish - Costa Ricaes-cr
Spanish - Dominican Republices-do
Spanish - Ecuadores-ec
Spanish - El Salvadores-sv
Spanish - Guatemalaes-gt
Spanish - Hondurases-hn
Spanish - Mexicoes-mx
Spanish - Nicaraguaes-ni
Spanish - Panamaes-pa
Spanish - Paraguayes-py
Spanish - Perues-pe
Spanish - Puerto Ricoes-pr
Spanish - Spain (Traditional)es-es
Spanish - Uruguayes-uy
Spanish - Venezuelaes-ve
Swahilisw
Swedish - Finlandsv-fi
Swedish - Swedensv-se
Tajiktg
Tamilta
Tatartt
Telugute
Thaith
Tibetanbo
Tsongats
Turkishtr
Turkmentk
Ukrainianuk
Urduur
Uzbek - Cyrillicuz-uz
Uzbek - Latinuz-uz
Vietnamesevi
Welshcy
Xhosaxh
Yiddishyi
Zuluzu

Currently there aren't local validators implemented. If you wish to develop one to support a specific country validation, please take a look at Implementing new Validators and Contributions topics.

Implementing new Validators

To create a new validator to your project, you should implement the Validator interface.

All validation rules must be inside of the validate method. For example:

import { Validator, ValidatorError } from '@orche/validators';

export class CustomValidator implements Validator {

  public validate(value: any, validatorParams?: any): Promise<ValidatorError> {
    // ... your validation rules  
  }

}

About the validate method:

The params:

  • value: this is the value that will be evaluated
  • validatorParams: this param may contains zero, one or more values. It can be used as a reference for the validation. For example: to check if a value is higher than other or a specific date.

Return value:

  • The method returns a Promise of ValidatorError. The reason to return a promise is for async execution of long processing validations, like going to DB to get a value or something that needs an extra processing.
  • If there is no validation error, the method must resolve nothing - resolve();
  • If there is a validation error, resolve a ValidatorError object, for example:
const validatorError: ValidatorError = {
  message: 'Validator Message [REQUIRED]',
  value: 'this is the validated value [OPTIONAL]',
  details: 'Add any details about the validation. [OPTIONAL]'
}

resolve(validatorError);

Important: Avoid to use external libraries, except those that are pretty generic like lodash or momentjs. This is for keeping away from excessive dependencies as it could result in bugs.

Share to the community

If you think that your validator can be used by others, please consider sharing to the communit. The first thing is to open an issue and after being accepted, submit your Pull Request.

Don't forget to take a look at the contribution guidelines.

Contributions

If you want to contribute to the project, please check out the contributing document.

Thanks for supporting Orchejs!

License

MIT License

Copyright (c) 2017 Mauricio Gemelli Vigolo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.