@sbcore/ng-absolute-validator
v14.1.1
Published
A complete Angular form validation library — built-in, custom, and advanced/async validators for reactive and template-driven forms.
Maintainers
Readme
Angular Absolute Validator
Like no other form validation library, simply write in English your requirements inside your form HTML tags, Absolute Validator will do the rest.
Package renamed: this library was previously published as
ng-absolute-validator. It now lives at@sbcore/ng-absolute-validator— update your install command and imports to the new scoped name below. The old package name is deprecated and will no longer receive updates; existing installs keep working, but new features (including everything in this release) are only published under the new name.
New Features
- Language system simplified and improved — translation loading and merging are more robust, and easier to extend or override.
- Seamless integration with your own translations —
ng-absolute-validatornow automatically merges its language data into your existing TranslateService instance, so you can bring your own translation setup as-is, with no extra configuration required. fallbackLanguageremoved —defaultLanguagenow serves as the fallback when a translation key is missing, so there's no need to configure both separately.showErrorOnintroduced — control when validation errors appear (touched,dirty,submit, oralways), configured globally.showAllErrorsintroduced — choose whether to show every failing rule at once or stop at the first invalid one.- Validation error results now expose a richer object —
i18nKey,args,attr,message, andlang— giving you full context (which rule failed, its arguments, the field name, the translated text, and the language it's in) instead of just a message string.
Documentation & Support
- Go to Full Documentation
- Go to For Support
Installation
To install this library, run:
$ npm install @sbcore/[email protected]Upgrading from the old package? Uninstall the deprecated name first:
npm uninstall ng-absolute-validator, then install@sbcore/ng-absolute-validatoras above and update every import in your project to match (see below).
Import FormsModule, ReactiveFormsModule and NgAbsoluteValidatorModule in your Angular AppModule. FormsModule is required for template-driven forms, ReactiveFormsModule is required for reactive forms (see the examples below) — import both if your app uses either style.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { NgAbsoluteValidatorModule } from '@sbcore/ng-absolute-validator';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
NgAbsoluteValidatorModule.forRoot({})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }Multi-language Error Messages
NgAbsoluteValidatorModule can render validation messages in more than one language: a project-wide message set is registered once at the application root, with a fallback language for anything not translated, and any single field can override or extend that message set inline.
Registering languages at the application root
Pass your message object and the active language to forRoot() when importing the module in AppModule:
import { NgModule } from '@angular/core';
import { NgAbsoluteValidatorModule } from '@sbcore/ng-absolute-validator';
@NgModule({
imports: [
NgAbsoluteValidatorModule.forRoot({
language: 'en',
defaultLanguage : 'en',
messages: {
en: {
required: 'The :attribute field is required.',
email: 'The :attribute must be a valid email address.',
above: 'The :attribute should be above :arg0.'
},
ar: {
required: 'حقل :attribute مطلوب.',
email: 'يجب أن يكون :attribute بريدًا إلكترونيًا صالحًا.'
}
}
})
]
})
export class AppModule { }Falling back to a default language
If the active language has no message defined for a rule that fails, the library looks it up in defaultLanguage instead of showing a blank or missing message. In the example above, an Arabic-language user who fails the above rule sees the English fallback message, since the ar message set never defines one for above.
Inline, per-field message overrides
A single field can override — or add — messages without touching the root configuration, by passing a message object as the second argument to rv.map(). It only affects that field:
public aboveMessage: any = {
en: { above: 'The :attribute should be above :arg0.' },
ar: { above: 'ال :attribute يجب أن يكون أعلاه :arg0.' }
}
public formRules = {
above: ['', this.rv.map('above:20', this.aboveMessage)],
// ...
}Use this when one field needs custom wording that shouldn't apply to every other field using the same rule elsewhere in the app.
Add CSS Style for color effect on validation
Add CSS style to application style.css file to get color effect on validation.
.ng-invalid:not(form):not(.ng-untouched){
border: 1px solid red;
}
.ng-valid:not(form){
border: 1px solid green;
}Template driven form validation Example
Once your library is imported, you can use the validation display message component and directive to activate the validation process.
<!-- For directive use, with no chain rules -->
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input type="text" name="<name>" [(ngModel)]="<name>" #<name>="ngModel">
<ng-absolute-validator [formInstance]="<name>" (onValid)="getStatus($event)"></ng-absolute-validator>
</form>
<!-- For Chain validation -->
<form (ngSubmit)="onSubmit(form)" #form="ngForm">
<input rule="required|integer|above:20" type="text" name="<name>" [(ngModel)]="<name>" #<name>="ngModel">
<ng-absolute-validator [formInstance]="<name>" (onValid)="getStatus($event)"></ng-absolute-validator>
</form>Reactive form validation Example
import { Component } from '@angular/core';
import { ReactiveValidator } from '@sbcore/ng-absolute-validator';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive',
templateUrl: './reactive.component.html',
styleUrls: ['./reactive.component.css']
})
export class ReactiveComponent {
public form: FormGroup;
public formRules: { [key: string]: any };
public aboveMessage: any = {
en: { above: 'The :attribute should be above :arg0.' },
ar: { above: 'ال :attribute يجب أن يكون أعلاه :arg0.' }
}
constructor(
private fb: FormBuilder,
private rv: ReactiveValidator,
) {
this.formRules = {
above: ['', this.rv.map('above:20', this.aboveMessage)],
dimension: ['',
this.rv.map('image'),
this.rv.dimension('width=200px,height=200px')
],
email: ['',
this.rv.map('email'),
this.rv.unique({ url: 'http://jsonplaceholder.typicode.com/users' })
],
}
this.form = this.fb.group(this.formRules);
}
}Validation Rules
All validation rules and error message details are given in the documentation: Full Documentation
The Rule column is the name of the validation rule. the Usage column is the exact string you write inside rule="..." or rv.map('...') — note that multi-word rules use snake_case there, not camelCase.
| Rules | Usage | Description |
| :--- | :--- | :--- |
|above|above:20|Makes sure the value provided by the end user is above the expected value. This method will wrapboth the values|
|accepted|accepted|Ensures that the field under validation is accepted. Empty strings, false, null, 0 and undefinedvalues will be considered as not accepted.|
|after|after:12-01-1991|Ensures the value of the field is after the expected date.|
|alpha|alpha|Makes sure the field under validation is alpha only.|
|alphaDash|alpha_dash|Makes sure the field under validation is contain letters, numbers, dashes and underscores.|
|alphaNumeric|alpha_numeric|Makes sure the field under validation is alpha numeric only.|
|array|array|Ensure the value is a valid array. Also this validation will never validate the size of array.|
|before|before:12-01-1991|Ensures the value of field under validation is before a given date.|
|between|between:5,10|Ensures a numeric value falls strictly between the two given bounds, exclusive of both endpoints(so between:5,10 accepts 6-9 but rejects 5 and 10). Unlike range, the boundary values themselvesare not accepted.|
|boolean|boolean|Ensures the value of a field is a boolean. Also it will cast following strings to their booleancounter parts.|
|confirmed|confirmed|Ensures a field value as confirmed using a _confirmation convention. This is mainly used forpassword confirmation field.For example: If the password field name is password, then another field called password_confirmationmust exist and should have the same value as the actual field.|
|creditCard|credit_card|Ensures a field value must be a valid credit card number.|
|cvv|cvv|Ensures a field value must be a CVV number.|
|date|date|Ensures the field under validation is a valid date. The value can be a date object or a valid datestring.|
|dateFormat|date_format:DD-MM-YYYY|Ensures the date or date time is valid as the one of the defined formats.|
|debitCard|debit_card|Ensures a field value must be a valid debit card number.|
|different|different:other_field|Ensures the value of the field under validation is always different from the targeted field value.|
|dimension|rv.dimension('width=200px,height=200px')|Ensures the The file under validation must be an image meeting the dimension constraints asspecified by the accppeted params like: height=200,max_height=200,width=200,max_width=200,ratio=1.2. Passed as its own call, not inside the rule chain — see the reactive form example above.|
|email|email|Ensures the field under validation is a valid email format.|
|endsWith|ends_with:a,b|Ensure the value of field under validation ends with a certain substr. This validation will alsotrim whitespaces before making the check|
|equals|equals:a|Ensures the value of the field under validation exactly matches the given value.|
|exists|rv.exists({url:'...'})|Ensures the value exists in the database. Only GET and POST methods areallowed for remote validation; the default method is GET. Passed as its own call, not inside the rule chain.|
|image|image|Ensures the upload file is an valid image file|
|in|in:a,b|Ensures the value of a given field matches one of expected values.|
|includes|includes:abcd,efgh|Ensures the value of field under validation contains a given substring.|
|integer|integer|Ensures the value is a valid integer. Also string representation of a number will return true.|
|ip|ip|Ensures the value is a valid ip address as per ipv4 and ipv6 specs.|
|ipv4|ipv4|Ensures the value is a valid ip address as per ipv4 spec only.|
|ipv6|ipv6|Ensures the value is a valid ip address as per ipv6 spec only.|
|json|json|Ensures the value of field under validation is safe to be parsed using JSON.parse method.|
|max|max:10|Ensures the length of a string or array or number is not greater than the defined length.|
|min|min:10|Ensures the length of a string or array or number is not is not less than the expected length|
|mimes|mimes:png,jpg|Ensures the file must have a MIME type corresponding to one of the listed extensions.|
|notEquals|not_equals:10|Makes sure that the value of field under validation is not same as the defined value.|
|notIn|not_in:a,b,c|Makes sure that the value of field under validation is not from one of the defined values.|
|notRegex|not_regex:(?=.*[0-9])|Ensures the value of field under validation, passes the regex test. The regex can be defined as astring or a RegExp object.|
|number|number|Makes sure that the value of field under validation is a valid number. The validation will pass forfloats too, since it uses typeof internally.|
|phoneNo|phone_no|Makes sure that the value of field under validation is a valid phone number. In default phone numberis validate more than 10 Style of number.To override the default behaviour pass new regex expressionto validate the number.|
|range|range:5,10|Ensures the value of field under validation is under a given range. The values will be cased toNumber automatically.|
|regex|regex:(?=.*[0-9])|Ensures the value of field under validation, passes the regex test. The regex can be defined as astring or a RegExp object.|
|required|required|Ensures the value of field under validation is not empty.|
|requiredIf|required_if:field,value|Ensures the field under validation must be present and not empty if the anotherfield field is equalto any value. The Match with field must be define or initialized or placed before validated field.|
|requiredUnless|required_unless:field,value|Ensures the field under validation must be present and not empty unless the anotherfield field isequal to any value. The Match with fields must be define or initialized or placed before validatedfield.|
|requiredWith|required_with:field1,field2|Ensure The field under validation must be present and not empty only if any of the other specifiedfields are present. The Match with fields must be define or initialized or placed before validatedfield.|
|requiredWithAll|required_with_all:field1,field2|Ensure The field under validation must be present and not empty only if all of the other specifiedfields are present. The Match with fields must be define or initialized or placed before validatedfield.|
|requiredWithout|required_without:field1,field2|Ensure The field under validation must be present and not empty only when any of the other specifiedfields are not present. The Match with fields must be define or initialized or placed beforevalidated field.|
|requiredWithoutAll|required_without_all:field1,field2|Ensure The field under validation must be present and not empty only when all of the other specifiedfields are not present. The Match with fields must be define or initialized or placed beforevalidated field.|
|same|same:other_field|Ensures the value of 2 fields are same.|
|size|size:120|Ensures the size of the file not more than the specific size (in KB).|
|startsWith|starts_with:a,b|Ensures the value of 2 fields are same.|
|string|string|Ensures the value is a string.|
|strength|strength| Make sure the value strength should mach pre defined regex expression. Add or overide with new regex expression from root config. Add or modify progess bar color combination from root config. a : String must be 8 charecter long. b : String must contain one uppercase letter. c : String must contain one spatial charecter. d : String must contain one digit. b : String must contain one lowecase letter. |
|under|under:10|Ensures the value of a field is under a certain value. All values will be casted to Number|
|url|url|Ensures the value is a valid URL format.|
|uuid|uuid|Ensures the value is a valid UUID format.|
|unique|rv.unique({url:'...'})|Ensures the value is unique in the database. Only GET and POST methods areallowed for remote validation; the default method is GET. Passed as its own call, not inside the rule chain.|
|video|video|Ensures the upload file is an valid video file|
License
This project is licensed under the terms of the MIT license.
