Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
@rxweb/reactive-form-validators
Advanced tools
[![Build Status](https://dev.azure.com/ajayojha/rxweb/_apis/build/status/rxweb-CI?branchName=master)](https://dev.azure.com/ajayojha/rxweb/_build/latest?definitionId=39&branchName=master) [![Gitter](https://badges.gitter.im/rx-web/Lobby.svg)](https://git
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
Which Version to use?
Angular version | Reactive Form Validators version |
---|---|
Angular >= 13 | @rxweb/reactive-form-validators@13.x |
Angular <= 12 | less than @rxweb/reactive-form-validators@13.x |
Reactive Form Validators will work in angular projects.
$ npm install @rxweb/reactive-form-validators
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 { }
Three ways to apply validation on the form via Validators, Validation Decorators or Template Form.
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 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;
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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;
file validation validators allows user to validate whether how many files can be uploaded . It depends upon maxFiles and minFiles.
Reactive Form Validation
this.userInfoFormGroup = this.formBuilder.group({
totalDocumentFiles:['', RxwebValidators.file({minFiles:5 })],
});
Template Form Validation
<input type="file" name="totalImageFiles" multiple [(ngModel)]="userinfo.totalImageFiles" class="form-control" [file]=" {'maxFiles':5}"/>
Decorator Based Validation
@file({maxFiles:5 })
totalImageFiles: number;
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;
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;
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 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;
ip validation validators is used to validate the ip address of the device.
Reactive Form Validation
this.userFormGroup = this.formBuilder.group({
ipV4:['', RxwebValidators.ip({version:1 })],
});
image validation validators allows user to validate image like height,width etc .
Reactive Form Validation
this.userInfoFormGroup = this.formBuilder.group({
profilePhoto:['', RxwebValidators.image({maxHeight:100 ,maxWidth:100 })],
});
Template Form Validation
<input type="file" name="profilePhoto" [(ngModel)]="userinfo.profilePhoto" class="form-control" [image]="{'maxHeight':100,'maxWidth':100}"/>
Decorator Based Validation
@image({maxHeight:100 ,maxWidth:100 })
profilePhoto: string;
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 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 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 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;
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;
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 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 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 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 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 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 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;
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 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 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 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 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 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 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 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 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({expression:{'onlyAlpha': /^[A-Za-z]+$/} })],
});
Template Form Validation
<input id="userName" name="userName" class="form-control"
[(ngModel)]="user.userName" [pattern]='{"expression":{'onlyAlpha': /^[A-Za-z]+$/}}' >
Decorator Based Validation
@pattern({expression:{'onlyAlpha': /^[A-Za-z]+$/} }) userName: string;
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 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 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 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 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 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;
Unique validation validators is used to validate unique input based on formArray.
Reactive Form Validation
this.employeeFormGroup = this.formBuilder.group({
fullName:[''],
skills:this.formBuilder.array([
this.getSkillFormGroup()
])
});
addSkill(){
let skillsArray = <FormArray>this.employeeFormGroup.controls.skills;
skillsArray.push(this.getSkillFormGroup());
}
getSkillFormGroup(){
return this.formBuilder.group({
skillName:['',RxwebValidators.unique()]
})
}
Decorator Based Validation
@unique()
skillName: string[];
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 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;
Remove the characters form the user entered value.
@prop()
@blacklist('abc' )
freeText: string;
Trim characters from the left-side of the input.
@prop()
@ltrim()
freeText: string;
Trim characters from the right-side of the input.
@prop()
@rtrim()
freeText: string;
Convert the input to a boolean.
@prop()
@toBoolean()
Active: boolean;
Convert the input to a date, or null if the input is not a date.
@prop()
@toDate()
dob: Date;
Convert the input to a float, or NAN if the input is not a float.
@prop()
@toDouble()
amount: number;
Convert the input to an integer, or NAN if the input is not an integer.
@prop()
@toInt()
amount: number;
Convert the input to a string.
@prop()
@toString()
freeText: string;
Trim characters from the input.
@prop()
@trim()
freeText: string;
Remove characters that do not appear in the whitelist.
@prop()
@whitelist('abc' )
freeText: string;
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 retrieve 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}
));
})
}
}
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'})]]
});
}
}
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>
This provides a toFormData()
method which converts the FormGroup value into the FormData. Here is an example of Post as FormData of Reactive Form value. See the working code example on stackblitz
Reactive Form Validation
this.userFormGroup = this.formBuilder.group({
firstName:[''],
lastName :[''],
userName:[''],
password : ['']
});
addUser(){
let formdata = this.userFormGroup.toFormData()
this.http.post(this.api, formdata); // This is fake uri, This is just for your reference.
}
To create fileObject from the input we have to set writeFile="true" attribute on the HTMLInputFileElement. Here is an example of Post Image through formData. See the working code example on stackblitz
Reactive Form Validation
this.userInfoFormGroup = this.formBuilder.group({
profilePhoto:[''],
});
addUser(){
let formdata = (<FormGroupExtension>this.userInfoFormGroup).toFormData()
this.http.post(this.api, formdata); // This is fake uri, This is just for your reference.
}
<input type="file" [writeFile]="true" formControlName="profilePhoto" class="form-control" multiple />
RxFormBuilder provide a solution for reset form of angular reactive form object. If you want to reset the form as per the value initialized while creating an instance of the formControls, you can use resetForm()method of FormGroupExtension. See the working code example on stackblitz
Reactive Form Validation
this.userFormGroup = this.formBuilder.group({
firstName:[''],
lastName:[''],
userName:[''],
password:['']
});
resetForm(){
(<FormGroupExtension>this.userFormGroup).resetForm();
}
Compare validation is used to check whether the value of two formControls are same or not .Here is an example of comparing password. field. See the working code example on stackblitz
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;
You can a single default message for a formControl and display it in single errormessage without multiple conditions stackblitz
<input type="text" formControlName="userName" class="form-control" />
{{userFormGroup.controls.userName["errorMessage"]}}
In ReactiveFormConfig set the global validation message
"validationMessage":{
"required":"This field is required",
"minLength":"minimum length is {{0}}",
"maxLength":"allowed max length is {{0}}"
}
});
this.userFormGroup = this.formBuilder.group({
userName:['',[RxwebValidators.required(),RxwebValidators.minLength({value:5}),RxwebValidators.maxLength({value:10})]]
})
If you are thinking to make rxweb framework better, that's truly great. You can contribute from a single character to core architectural work or significant documentation – all with the goal of making a robust rxweb framework which helps for everyone in their projects. Even if you are don’t feel up to writing code or documentation yet, there are a variety of other ways that you can contribute like reporting issues to testing patches.
Check out the docs on how you can put your precious efforts on the rxweb framework and contribute in the respective area.
We highly recommend for help please ask your questions on our gitter/rxweb-project to get quick response from us. Otherthan our gitter channel you can ask your question on StackOverflow or create a new issue in our Github Repository.
For, issue please refer our issue workflow wiki for better visibility our issue process.
You can request a new feature by submitting an issue to our GitHub Repository. If you would like to implement a new feature, please submit an issue with a proposal for your work first, to be sure that we can use it.
MIT
FAQs
[![Build Status](https://dev.azure.com/ajayojha/rxweb/_apis/build/status/rxweb-CI?branchName=master)](https://dev.azure.com/ajayojha/rxweb/_build/latest?definitionId=39&branchName=master) [![Gitter](https://badges.gitter.im/rx-web/Lobby.svg)](https://git
The npm package @rxweb/reactive-form-validators receives a total of 16,167 weekly downloads. As such, @rxweb/reactive-form-validators popularity was classified as popular.
We found that @rxweb/reactive-form-validators demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.