New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@rxweb/reactive-form-validators

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rxweb/reactive-form-validators

[![Build Status](https://travis-ci.org/rxweb/rxweb.svg?branch=master)](https://travis-ci.org/rxweb/rxweb) [![Gitter](https://badges.gitter.im/rx-web/Lobby.svg)](https://gitter.im/rxweb-project/rxweb?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge

  • 1.4.6
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
20K
decreased by-9.82%
Maintainers
1
Weekly downloads
 
Created
Source

Build Status Gitter GitHub license Codacy Badge dependencies Status npm version

rxweb

The most powerful validation framework for angular based enterprise application. This provides all type of complex validation and dynamic validation on Reactive Form, Template Driven Form and Model Based Form.

Angular forms provides good feature, but at some level code become messy to fulfil the complex validation scenarios, so the core objective is to provide optimum solution for basic, complex, conditional and dynamic validation for angular based enterprise applications. This validation framework is an extension of angular forms library, which will help to fulfil the need with less lines of code.

For More Information on rxweb

Prerequisites

Reactive Form Validators will work in angular projects.

Table of Contents

Installation

$ npm install @rxweb/reactive-form-validators

Import modules

To work on form it is require to import angular modules(FormsModule and ReactiveFormsModule) and also import RxReactiveFormsModule which provides advanced/dynamic level validation features. All three modules register in the NgModule decorator imports property.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { FormsModule, ReactiveFormsModule} from '@angular/forms'; // <-- #1 import module
import { RxReactiveFormsModule } from '@rxweb/reactive-form-validators'; // <-- #2 import module


import {AppComponent} from './app.component';

@NgModule({
  declarations:[AppComponent],
  imports:[ BrowserModule, 
	FormsModule,
	ReactiveFormsModule, 
	RxReactiveFormsModule
	] 
  providers: [], 
  bootstrap: [AppComponent]
})
export class AppModule { }

Form Validation

Three ways to apply validation on the form via Validators, Validation Decorators or Template Form.

  1. allOf
  2. alpha
  3. alphaNumeric
  4. ascii
  5. choice
  6. compare
  7. compose
  8. contains
  9. creditCard
  10. dataUri
  11. different
  12. digit
  13. email
  14. endsWith
  15. even
  16. extension
  17. factor
  18. fileSize
  19. greaterThanEqualTo
  20. greaterThan
  21. hexColor
  22. json
  23. latitude
  24. latLong
  25. leapYear
  26. lessThanEqualTo
  27. lessThan
  28. longitude
  29. lowerCase
  30. mac
  31. maxDate
  32. maxLength
  33. maxNumber
  34. minDate
  35. minLength
  36. minNumber
  37. noneOf
  38. numeric
  39. odd
  40. oneOf
  41. password
  42. pattern
  43. port
  44. primeNumber
  45. range
  46. required
  47. startsWith
  48. time
  49. upperCase
  50. url

allOf

allOf validation will check whether the user has entered all of the values of given field or not.

Reactive Form Validation

  this.employeeInfoFormGroup = this.formBuilder.group({
           skills:[RxwebValidators.allOf({matchValues:["MVC", "AngularJS","AngularJS 5","C#"]})], 
        });

Template Form Validation

 <input id="skills"  name="skills" type="checkbox" value="{{tag.name}}" 
        [(ngModel)]="employee.skills" [allOf]='{"matchValues":"MVC","AngularJS","AngularJS","C#"}'/>{{tag.name}}

Decorator Based Validation

  @allOf({matchValues: ["MVC", "AngularJS","Angular 5","C#"]}) skills: string[];

alpha

Alpha validation will allow only alphabets to be entered. It will not allow any digit or special character.

Reactive Form Validation

this.countryFormGroup = this.formBuilder.group({
            countryName:['', RxwebValidators.alpha()], 
        });

Template Form Validation

<input id="countryName" name="countryName" class="form-control"
         [(ngModel)]="country.countryName" alpha >

Decorator Based Validation

@alpha() countryName: string;

alphaNumeric

Alpha Numeric validation will allow only alphabets and numbers to be entered, It will not allow any special character.

Reactive Form Validation

  this.locationFormGroup = this.formBuilder.group({
            areaName:['', RxwebValidators.alphaNumeric()], 
        });

Template Form Validation

<input id="areaName" name="areaName" class="form-control"
         [(ngModel)]="location.areaName" alphaNumeric >

Decorator Based Validation

@alphaNumeric() areaName: string;

ascii

ascii validation decorator allows user to enter the input which is in the proper ascii format.

Reactive Form Validation

   this.userFormGroup = this.formBuilder.group({
            specialCharAsciiCode:['', RxwebValidators.ascii()], 
        });

Template Form Validation

<input id="specialCharAsciiCode" name="specialCharAsciiCode" class="form-control"
         [(ngModel)]="user.specialCharAsciiCode" ascii >

Decorator Based Validation

@ascii() specialCharAsciiCode: string;

choice

choice validation will check whether the value entered is matching the properties defined.

Reactive Form Validation

  this.employeeInfoFormGroup = this.formBuilder.group({
           skills:[RxwebValidators.choice({minLength:5})], 
        });

Template Form Validation

 <input id="skills"  name="skills" type="checkbox" value="{{tag.name}}"
        [(ngModel)]="employee.skills" [choice]='{"minLength":"5"}'/>{{tag.name}}

Decorator Based Validation

 @choice({minLength:'5'}) skills: string[]; 

compare

Compare validation will compare two inputs whether they are same or not.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            password:['',], 
            confirmPassword:['', RxwebValidators.compare({fieldName:'password' })], 
        });

Template Form Validation

<input id="confirmPassword" name="confirmPassword" class="form-control"
         [(ngModel)]="user.confirmPassword" [compare]='{"fieldName":"password"}'] >

Decorator Based Validation

@compare({fieldName:'password'}) confirmPassword: string;

compose

Compose validation decorator is used to apply multiple validations on a particular field.

Reactive Form Validation

this.userForm = this.formBuilder.group({
  Username:['',[ RxwebValidators.compose({
validators:[
RxwebValidators.required(),
RxwebValidators.alpha()
],]]
});

Template Form Validation

<input id="Username" name="Username" class="form-control"
         [(ngModel)]="user.Username" [compose]='{"validators":[alpha,required]}' >

Decorator Based Validation

@compose({validators:[alpha,required]}) Username: string;

contains

Contains validation will check that value is in the input, It will not allow to enter input that not contains the predefined value.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            emailAddress:['', RxwebValidators.contains({value:'@gmail.com' })], 
        });

Template Form Validation

<input id="emailAddress" name="emailAddress" class="form-control"
         [(ngModel)]="user.emailAddress" [contains]='{"fieldName":"@gmail.com"}' >

Decorator Based Validation

@contains({value:'@gmail.com'}) emailAddress: string;

creditCard

creditCard validation will check property value is creditcardtype or not, It will not allow to enter any value other than credit card format.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            cardType:['',], 
            creditCardNumber:['', RxwebValidators.creditCard({fieldName:'cardType' })], 
        });

Template Form Validation

<input id="creditCardNumber" name="creditCardNumber" class="form-control"
         [(ngModel)]="user.creditCardNumber" [creditCard]='{"fieldName":"cardType"}' >

Decorator Based Validation

@creditCard({fieldName:'cardType' }) creditCardNumber: string;

dataUri

dataUri validation allows user to enter the input which is a valid data Uri.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            htmlDataUri:['', RxwebValidators.dataUri()], 
        });

Template Form Validation

<input id="htmlDataUri" name="htmlDataUri" class="form-control"
         [(ngModel)]="user.htmlDataUri" dataUri >

Decorator Based Validation

@dataUri() htmlDataUri: string;

different

Different validation will check two inputs whether they are different or not. It is just opposite of compare decorator.

Reactive Form Validation

 this.accountInfoFormGroup = this.formBuilder.group({
            firstName:['',], 
            lastName:['', RxwebValidators.different({fieldName:"firstName" })], 
        });

Template Form Validation

<input id="lastName" name="lastName" class="form-control"
         [(ngModel)]="account.lastName" [different]='{"fieldName":"firstName"}' >

Decorator Based Validation

@different({fieldName:"firstName" }) lastName: string;

digit

Digit validation will allow only digits to be entered, It will not allow any alphabets or special character.

Reactive Form Validation

   this.userFormGroup = this.formBuilder.group({
            age:['', RxwebValidators.digit()], 
        });

Template Form Validation

<input id="age" name="age" class="form-control"
         [(ngModel)]="user.age" digit >

Decorator Based Validation

@digit() age: number;

email

Email validation will only allow user to enter input which is in the correct email format.

Reactive Form Validation

   this.userFormGroup = this.formBuilder.group({
            email:['', RxwebValidators.email()], 
        });

Template Form Validation

<input id="email" name="email" class="form-control"
         [(ngModel)]="user.email" email >

Decorator Based Validation

@email() email: string;

endsWith

endsWith validation allows user to enter the input which ends with particular value.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            name:['', RxwebValidators.endsWith({value:'m' })], 
        });

Template Form Validation

<input id="name" name="name" class="form-control"
         [(ngModel)]="user.name" [endsWith]='{"value":"m"}' >

Decorator Based Validation

@endsWith({value:'m' }) name: string;

even

Even validation will check whether the value entered by user is an even number or not.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            evenNumber:['', RxwebValidators.even()], 
        });

Template Form Validation

<input id="evenNumber" name="evenNumber" class="form-control"
         [(ngModel)]="user.evenNumber" even >

Decorator Based Validation

@even() evenNumber: number;

extension

extension validation allows user to enter the input which is in the proper extension format.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            Image :['', RxwebValidators.extension({extensions:'png','jpg'})], 
        });

Template Form Validation

<input id="Image" name="Image" class="form-control"
         [(ngModel)]="user.Image" [extension]='{"extensions":"png":"jpg"}' >

Decorator Based Validation

@extension({extensions:'png','jpg'}) Image: string;

factor

factor validation will allow user to enter factor of a number which is called dividend.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            firstNumber:['', RxwebValidators.factor({dividend:50 })], 
        });

Template Form Validation

<input id="firstNumber" name="firstNumber" class="form-control"
         [(ngModel)]="user.firstNumber" [factor]='{"dividend":"50"}' >

Decorator Based Validation

@factor({dividend:50 })	firstNumber: Number;

fileSize

fileSize validation allows user to enter the input which is in the proper file size format.

Reactive Form Validation

   this.storageCapacityFormGroup = this.formBuilder.group({
            videoStorageSize:['', RxwebValidators.fileSize({maxSize:50 })], 
        });

Template Form Validation

<input id="videoStorageSize" name="videoStorageSize" class="form-control"
         [(ngModel)]="storage.videoStorageSize" [fileSize]='{"maxSize":"50"}' >

Decorator Based Validation

@fileSize({maxSize:50 }) videoStorageSize: string;

greaterThanEqualTo

Greater than equal to validation decorator will check that input property is greater than or equal to the related field input.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            age:['',], 
            voterAge:['', RxwebValidators.greaterThanEqualTo({fieldName:'age' })], 
        });

Template Form Validation

<input id="voterAge" name="voterAge" class="form-control"
         [(ngModel)]="user.voterAge" [greaterThanEqualTo]='{"fieldName":"age"}' >

Decorator Based Validation

@greaterThanEqualTo({fieldName:'age' }) voterAge: number;

greaterThan

Greater than validation will check that input property is greater than related field input.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            age:['',], 
            voterAge:['', RxwebValidators.greaterThan({fieldName:'age' })], 
        });

Template Form Validation

<input id="voterAge" name="voterAge" class="form-control"
         [(ngModel)]="user.voterAge" [greaterThan]='{"fieldName":"age"}' >

Decorator Based Validation

@greaterThan({fieldName:'age' }) voterAge: number;

hexColor

HexColor validation will allow user to enter only the input in proper Hex Color format.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            color:['', RxwebValidators.hexColor()], 
        });

Template Form Validation

<input id="color" name="color" class="form-control"
         [(ngModel)]="user.color" hexColor >

Decorator Based Validation

@hexColor() color: string;

json

json validation will allow user to enter the input only in proper Json format.

Reactive Form Validation

 this.jsonInfoFormGroup = this.formBuilder.group({
            locationJson:['', RxwebValidators.json()], 
        });

Template Form Validation

<input id="locationJson" name="locationJson" class="form-control"
         [(ngModel)]="json.locationJson" json >

Decorator Based Validation

@json() locationJson: string;

latitude

latitude validation allows user to enter value which is valid latitude.

Reactive Form Validation

this.numberInfoFormGroup = this.formBuilder.group({
            firstCountryLatitude:['', RxwebValidators.latitude()], 
        });

Template Form Validation

<input id="firstCountryLatitude" name="firstCountryLatitude" class="form-control"
         [(ngModel)]="number.firstCountryLatitude" latitude >

Decorator Based Validation

@latitude() firstCountryLatitude: string;

leapYear

LeapYear validation will check whether the value entered is a leap year or not.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            birthYear:['', RxwebValidators.leapYear()], 
        });

Template Form Validation

<input id="birthYear" name="birthYear" class="form-control"
         [(ngModel)]="user.birthYear" leapYear >

Decorator Based Validation

@leapYear() birthYear: number;

latLong

latLong validation allows user to enter the input which is valid Latitude or longitude.

Reactive Form Validation

 this.countryFormGroup = this.formBuilder.group({
            firstCountry:['', RxwebValidators.latLong()], 
        });

Template Form Validation

<input id="firstCountry" name="firstCountry" class="form-control"
         [(ngModel)]="country.firstCountry" latLong >

Decorator Based Validation

@latLong() firstCountry: string;

lessThanEqualTo

Less than equal to validation will allow the user to enter only that value which is less than oe equal to the value in the pre defined field.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            totalMarks:['',], 
            marks:['', RxwebValidators.lessThanEqualTo({fieldName:'totalMarks' })], 
        });

Template Form Validation

<input id="marks" name="marks" class="form-control"
         [(ngModel)]="user.marks" [lessThanEqualTo]='{"fieldName":"totalMarks"}' >

Decorator Based Validation

@lessThanEqualTo({fieldName:'totalMarks' }) marks: number;

lessThan

Less than validation will allow the user to enter only that value which is less than the value in the pre defined field.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            marks:['',], 
            passingMarks:['', RxwebValidators.lessThan({fieldName:'marks' })], 
        });

Template Form Validation

<input id="passingMarks" name="passingMarks" class="form-control"
         [(ngModel)]="user.passingMarks" [lessThan]='{"fieldName":"marks"}' >

Decorator Based Validation

@lessThan({fieldName:'marks' }) passingMarks: number;

longitude

longitude validation allows user to enter the input which is in the proper longitude format.

Reactive Form Validation

   this.numberInfoFormGroup = this.formBuilder.group({
            firstCountryLongitude:['', RxwebValidators.longitude()], 
        });

Template Form Validation

<input id="firstCountryLongitude" name="firstCountryLongitude" class="form-control"
         [(ngModel)]="number.firstCountryLongitude" longitude >

Decorator Based Validation

@longitude() firstCountryLongitude: string;

lowercase

lowerCase validation will allow user to enter only the lowercase alphabets.

Reactive Form Validation

     this.userInfoFormGroup = this.formBuilder.group({
            username:['', RxwebValidators.lowerCase()], 
        });

Template Form Validation

<input id="username" name="username" class="form-control"
         [(ngModel)]="user.username" lowercase >

Decorator Based Validation

@lowerCase() username: string;

mac

mac validation will check whether the value entered is a valid mac address.

Reactive Form Validation

     this.macAddressInfoFormGroup = this.formBuilder.group({
            systemMacAddress:['', RxwebValidators.mac()], 
        });

Template Form Validation

<input id="systemMacAddress" name="systemMacAddress" class="form-control"
         [(ngModel)]="macAddress.systemMacAddress" mac >

Decorator Based Validation

@mac() systemMacAddress: string;

maxDate

MaxDate validation will allow user to enter the date less than the maxDate value parameter.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            registrationDate:['', RxwebValidators.maxDate({value:new Date(2018,7,30) })], 
        });

Template Form Validation

<input id="registrationDate" name="registrationDate" class="form-control"
         [(ngModel)]="user.registrationDate" [maxDate]='{"value":"2018-07-30"}' >

Decorator Based Validation

@maxDate({value:new Date(2018,7,30) }) registrationDate: Date;

maxLength

MaxLength validation will allow user to enter the input upto the maximum length value parameter.

Reactive Form Validation

  this.locationFormGroup = this.formBuilder.group({
            firstName:['', RxwebValidators.maxLength({value:10 })], 
        });

Template Form Validation

<input id="firstName" name="firstName" class="form-control"
         [(ngModel)]="location.firstName" [maxLength]='{"value":"10"}' >

Decorator Based Validation

@maxLength({value:10 })	firstName: string;

maxNumber

MaxNumber validation will allow user to enter the input upto the maximum number value parameter.

Reactive Form Validation

 this.subjectDetailsFormGroup = this.formBuilder.group({
            passingMarks:['', RxwebValidators.maxNumber({value:50 })], 
        });

Template Form Validation

<input id="passingMarks" name="passingMarks" class="form-control"
         [(ngModel)]="subject.passingMarks" [maxNumber]='{"value":"50"}' >

Decorator Based Validation

@maxNumber({value:50 }) passingMarks: number;

minDate

Minimum Date validation will allow user to enter date greater the minimum date value parameter.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            registrationDate:['', RxwebValidators.minDate({value:new Date(2018,7,30) })], 
        });

Template Form Validation

<input id="registrationDate" name="registrationDate" class="form-control"
         [(ngModel)]="user.registrationDate"  [minDate]='{"value":"2018-07-30"}' >

Decorator Based Validation

@minDate({value:new Date(2018,7,30) }) registrationDate: Date;

minLength

MinLength validation will allow user to enter the input length matching the minimum length value parameter.

Reactive Form Validation

this.contactFormGroup = this.formBuilder.group({
            countryName:['', RxwebValidators.minLength({value:8 })], 
        });

Template Form Validation

<input id="countryName" name="countryName" class="form-control"
         [(ngModel)]="country.countryName" [minLength]='{"value":"8"}' >

Decorator Based Validation

@minLength({value:8 }) countryName: string;

minNumber

MinNumber validation will allow user to enter the input greater than the minimum number value parameter.

Reactive Form Validation

  this.resultInfoFormGroup = this.formBuilder.group({
            maths:['', RxwebValidators.minNumber({value:35 })], 
        });

Template Form Validation

<input id="maths" name="maths" class="form-control"
         [(ngModel)]="result.maths" [minNumber]='{"value":"35"}' >

Decorator Based Validation

	@minNumber({value:35 }) maths: number;

noneOf

noneOf validation will check whether the user has entered none of the value is selected from the given inputs.

Reactive Form Validation

  this.employeeInfoFormGroup = this.formBuilder.group({
           skills:[RxwebValidators.noneOf({matchValues:["MVC", "AngularJS","Angular 5","C#"]})], 
        });

Template Form Validation

 <input id="skills"  name="skills" type="checkbox" value="{{tag.name}}" 
        [(ngModel)]="employee.skills" [noneOf]='{"matchvalues":"MVC","AngularJS","Angular 5","C#"}'/>{{tag.name}}

Decorator Based Validation

  @noneOf({matchValues: ["MVC", "AngularJS","Angular 5","C#"]})  skills: string[];

numeric

numeric validation will check whether the value entered is a valid numberic value or not.The validation can be set according to requirement, it can be either decimal,negative number or positive number.

Reactive Form Validation

 this.userInfoFormGroup = this.formBuilder.group({
            integerNumber:['', RxwebValidators.numeric({acceptValue:NumericValueType.PositiveNumber  ,allowDecimal:false })], 
        });

Template Form Validation

<input id="integerNumber" name="integerNumber" class="form-control"
         [(ngModel)]="user.integerNumber" [numeric]='{"acceptValue":"NumericValueType.PositiveNumber","allowDecimal":"false"}' >

Decorator Based Validation

	@numeric({acceptValue:NumericValueType.PositiveNumber  ,allowDecimal:false }) integerNumber: number;

odd

Odd validation will check whether the value entered is an odd number or not.

Reactive Form Validation

  this.userFormGroup = this.formBuilder.group({
            oddNumber:['', RxwebValidators.odd()], 
        });

Template Form Validation

<input id="oddNumber" name="oddNumber" class="form-control"
         [(ngModel)]="user.oddNumber" odd >

Decorator Based Validation

	@odd() oddNumber: number;

oneOf

oneOf validation will check whether the user has entered any one of the given inputs or not.

Reactive Form Validation

    this.employeeInfoFormGroup = this.formBuilder.group({
           skills:[RxwebValidators.oneOf({matchValues:["MVC", "AngularJS","Angular 5","C#"]})], 
        });

Template Form Validation

 <input id="skills"  name="skills" type="checkbox" value="{{tag.name}}" 
        [(ngModel)]="employee.skills" [oneOf]='{"matchvalues":"MVC","AngularJS","Angular 5","C#"}'/>{{tag.name}}

Decorator Based Validation

 @oneOf({matchValues: ["MVC", "AngularJS","Angular 5","C#"]}) skills: string[];

password

Password validation will allow user to enter only the input according to correct password validation format.

Reactive Form Validation

  this.loginInfoFormGroup = this.formBuilder.group({
            password:['', RxwebValidators.password({validation:{maxLength: 10,minLength: 5,digit: true,specialCharacter: true} })], 
        });

Template Form Validation

 <input id="password" name="password" class="form-control"
         [(ngModel)]="login.password" [password]='{"validation":{maxLength: 10,minLength: 5,digit: true,specialCharacter: true}}' >
 >

Decorator Based Validation

@password({validation:{maxLength: 10,minLength: 5,digit: true,specialCharacter: true} })	password: string;

pattern

Pattern validation will allow user to enter the input which match the predefined pattern value parameter.

Reactive Form Validation

this.userFormGroup = this.formBuilder.group({
            userName:['', RxwebValidators.pattern({pattern:{'onlyAlpha': RegExp('/^[A-Za-z]+$/')} })], 
        });

Template Form Validation

 <input id="userName" name="userName" class="form-control"
         [(ngModel)]="user.userName" [pattern]='{"pattern":{'onlyAlpha': RegExp('/^[A-Za-z]+$/')}}' >

Decorator Based Validation

	@pattern({pattern:{'onlyAlpha': RegExp('/^[A-Za-z]+$/')} }) userName: string;

port

port validation allows user to enter the input which is a valid port number.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            educationalWebsitePort:['', RxwebValidators.port()], 
        });

Template Form Validation

 <input id="educationalWebsitePort" name="educationalWebsitePort" class="form-control"
         [(ngModel)]="user.educationalWebsitePort" port >

Decorator Based Validation

		@port()	educationalWebsitePort: string;

primeNumber

primeNumber validation allows user to enter only prime number.

Reactive Form Validation

 this.numberInfoFormGroup = this.formBuilder.group({
            firstNumber:['', RxwebValidators.primeNumber()], 
        });

Template Form Validation

 <input id="firstNumber" name="firstNumber" class="form-control"
         [(ngModel)]="user.firstNumber" primeNumber >

Decorator Based Validation

	@primeNumber() firstNumber: string;

range

Range validation will check that the entered value is in the specified range

Reactive Form Validation

this.employeeInfoFormGroup = this.formBuilder.group({
            age:['', RxwebValidators.range({minimumNumber:18  ,maximumNumber:60 })], 
        });

Template Form Validation

 <input id="age" name="age" class="form-control"
         [(ngModel)]="employee.age" [range]='{"minimumNumber":"18","maximumNumber":"60"}' >

Decorator Based Validation

  @range({minimumNumber:18  ,maximumNumber:60 }) age: number;

required

Required validation will check that the user has entered the value in the property or not.

Reactive Form Validation

this.userInfoFormGroup = this.formBuilder.group({
            firstName:['', RxwebValidators.required()], 
        });

Template Form Validation

 <input id="firstName" name="firstName" class="form-control"
         [(ngModel)]="user.firstName" required >

Decorator Based Validation

 @required() firstName: string;

startsWith

startsWith validation allows user to enter the input which starts with particular value.

Reactive Form Validation

 this.userFormGroup = this.formBuilder.group({
            name:['', RxwebValidators.startsWith({value:'n' })], 
        });

Template Form Validation

 <input id="name" name="name" class="form-control"
         [(ngModel)]="user.name" [startsWith]='{"value":"n"}'>

Decorator Based Validation

 @startsWith({value:'n' }) name: string;

time

time validation will allow user to enter the input only in the correct time format.

Reactive Form Validation

  this.attandanceDetailFormGroup = this.formBuilder.group({
            entryTime:['', RxwebValidators.time()], 
        });

Template Form Validation

 <input id="entryTime" name="entryTime" class="form-control"
         [(ngModel)]="attandance.entryTime" time >

Decorator Based Validation

	@time() entryTime: string;

upperCase

UpperCase validation will allow user to enter the alphabets only in the upperCase format.

Reactive Form Validation

        this.locationFormGroup = this.formBuilder.group({
            countryName:['', RxwebValidators.upperCase()], 
        });

Template Form Validation

 <input id="countryName" name="countryName" class="form-control"
         [(ngModel)]="location.countryName" upperCase >

Decorator Based Validation

@upperCase() countryName: string;

url

Url validation will check that value entered in the property is in the correct url format or not.

Reactive Form Validation

      this.webSiteInfoModelFormGroup = this.formBuilder.group({
            adminWebsiteUrl:['', RxwebValidators.url()], 
        });

Template Form Validation

 <input id="adminWebsiteUrl" name="adminWebsiteUrl" class="form-control"
         [(ngModel)]="website.adminWebsiteUrl" url >

Decorator Based Validation

@url() adminWebsiteUrl: string;

Dynamic Validation

Dynamic validation is used, when the validation rules will come from server side, means there is no static code on client side to manage the validation on reactive form. Scenario : First Name field should accepts alphabets and that is configured on server side. Below is the json for validation rule for firstName field. See the working code example on stackblitz

dynamic-validation.json

{
"firstName":{
  "alpha":true
}
}

First of all retrive the validation rules from server and pass it to the group method.

user-info.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup } from "@angular/forms"
import { HttpClient } from '@angular/common/http';
import { RxFormBuilder, FormBuilderConfiguration } from '@rxweb/reactive-form-validators';


@Component({
    selector: 'app-user-info-add',
    templateUrl: './user-info-add.component.html'
})
export class UserInfoAddComponent implements OnInit {

    userInfoFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder,		private http: HttpClient
    ) { }

    ngOnInit() {
        this.http.get('assets/dynamic-validation.json').subscribe(                      (dynamicValidationConfiguration:any) => {
        
        this.userInfoFormGroup = this.formBuilder.group({
          firstName:['John']
        },
        new FormBuilderConfiguration( {dynamicValidation: dynamicValidationConfiguration}
                ));
})
    }
}

Conditional Validation

Some fields are required based on some other fields value, like if the firstName field contains the value of 'John' then the lastName field is required. see the working code example on stackblitz

import { Component, OnInit } from '@angular/core';
import { FormGroup } from "@angular/forms"

import { RxFormBuilder, RxwebValidators } from '@rxweb/reactive-form-validators';


@Component({
    selector: 'app-user-info-add',
    templateUrl: './user-info-add.component.html'
})
export class UserInfoAddComponent implements OnInit {

    userInfoFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder
    ) { }

    ngOnInit() {
        this.userInfoFormGroup = this.formBuilder.group({
          firstName:['',[RxwebValidators.required()]],
          lastName:['',[RxwebValidators.required({conditionalExpression:(x)=> x.firstName == 'John'})]]
        });
    }
}


Dirty Check

Check the form is dirty or not. On component side you have to create a FormGroup object via RxFormBuilder, afterthat you can use isDirty method from FormGroup object. See the dirty code example on stackblitz

<h3 class="bd-title" id="content">required Validator once for all properties</h3>
<br/>
<form [formGroup]="userInfoFormGroup">
<div class="form-group">
    <label>First Name</label>
    <input type="text" formControlName="firstName" class="form-control"  />
    <small class="form-text text-danger" >{{userInfoFormGroup.controls.firstName.errorMessage}}<br/></small>
</div>
<div class="form-group">
    <label>Last Name</label>
    <input type="text" formControlName="lastName" class="form-control"  />
    <small class="form-text text-danger" >{{userInfoFormGroup.controls.lastName.errorMessage}}<br/></small>
    
</div>
<button [disabled]="!userInfoFormGroup.isDirty()" class="btn btn-primary">Submit</button>
</form>

Upcoming Form Validations

  1. Masking.
  2. Phone/Mobile Number Masking.
  3. Countrywise Masking.
  4. Alphabet validation in other languages.
  5. AlphaNumeric validation in other languages.
  6. File Validation(size, extension, width and height validation).

Goal

  1. Provides all type of client side validations.
  2. Easy implementation of complex and dynamic validation with less lines of code.
  3. Faster development for Advanced/Complex validation Forms.

Help

We are happy to help you with any kind of validation related problem in angular based application. If you face any issue with the validation framework, you can follow one of the approach below :

  1. You can join our gitter chat room and solve your queries.
  2. You can log the issue on our github repository.
  3. Ask question on stackoverflow, we are active on stackoverflow.

If you need something different then the existing feature in the validation framework. Then you can create a feature request on our github repository.

Your Feedback

Your feedback is important for us, If you have any question or suggestion then please drop an email to ajay@rxweb.io.

License

MIT

Keywords

FAQs

Package last updated on 04 Jan 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc