Powerful Angular Form Verification Details

Angular supports very powerful built-in table verification, Maxlength, MinLength, Required, and Pattern. Using Angular’s built-in table verification can complete the verification requirements of the vast majority of business scenarios, but sometimes we need to achieve more complex form check function, then you can use Angular custom check (Custom Validator) ). Next, let’s take a look at how to use Angular custom form check

renderings:

强大的 Angular 表单验证功能详细介绍 1, first, to create us Registration component (register) and display a simple form

  

User Name:
In order to enable the form to be beautiful, the Bootstrap style file is introduced into index.html:
The code
code is as follows:

2, next to determine our Verification requirements: We hope that the username can only contain numbers, letters and underscores, and can not open the scribe

First add FormGroup instructions for the FORM tag:


, add formControlName instructions for the INPUT tag:


Copy code

The code is as follows:
    3, define verification rules in the code: 
Imported the following classes from the built-in form module:


Import {formbuilder, formgroup, validators} from ‘@ Angular / Forms’;

Where:
1. FormBuilder is used Build a form data
2. FormGroup Represents Form Type

3. Validators contains a form built-in verification rule, such as: Validators.Required


Define form single attribute

RegisterForm: formGroup;
   Errors messages that are displayed when the form is not passed (now we only have username) 

FORMERRORS = {UserName: ”};


For each verification rule, the description of the verification fails (form control may have multiple verification rules, by The validation note does not configure a wrong message)

ValidationMessage = {‘username’: {‘minlength’: ‘User name length is 3 characters,’ Maxlength ‘: The user name length is 10 characters’, ‘Required’: ‘Please fill in the username’}};


Add FB attributes to the constructorTo build form

   
Method for adding a building form

BuildForm (): void {// Build a form this.registerform = this.fb.register = this.fb.group ({/ * to add 3 verification rules for username: * 1. Required , 2. Maximum length is 10, 3. The minimum length is 3 * where the first empty string parameter is the default value of the form * / ‘username’: [‘, [Validators.Required, Validators.maxlength (10), Validators.MinLength (3)]});

Next we add a method to update the error message
   
OnValueChanged (data ?: any) {// If the form does not exist, return if (! This.register) return; // Get the current form const form = this.registerform; // Traverse the error message object for (Const Field In this.formerrors) {// Empty Current Error Message this.formerrorS [Field] = ”; // Gets the control const control = form.get (Field) of the current form; // The current form exists with this spatial control && The control is not modified && this control verificationIF (Control && Control.dirty &&! control.valid) {// Gets the control name that does not pass, in order to get more detailed information const message = this.validationMessage [Field]; // Traverse the error object of the current control Get the attribute for validation, for (const key in control.errors) {// put all verification does not pass the description text to the error message this.formerrorS [Field] + = Messages [Key] + ‘\ n’

The following only need to initialize the error message after the end of the form, and update the error message at each form data change
 Added code   
// update error message when the form data changes this.registerform.ValueChanges .subscribe (data = > this.onValueChanged (data)); // Initialization Error message this.onValueChanged ();
At this time, we have controlled the error message, below The display of the error message needs to be added to the form template can be

Add the following code below the INPUT tag:
   
{{ FormerRRORS.USERNAME}}

Add the following code to the form of CSS:
  Form {Width: 90%; Max-Width: 45em; margin: auto;} .showerr {White-space: pre-wrap;}  
Now let’s try to run, it is already possible to see a very good effect when the code is not reported


If the code error or no imagination, you can refer to The complete code ended in this article is modified

4, although we have built a whole layout, but has not yet implemented our ultimate goal: to achieve custom form verification
Next we create a regular verifier, New file validate-register.ts:
  Import {ValidatorFn, AbstractControl} from '@ Angular / Forms'; Export Function ValidateRex (Type: String, ValidateRex: Regex): ValidatorFN {return (Control: AbstractControl): {[key: string]: any} => {// Get the contents of the current control const str = control.value; // Set our custom verification type const res = {}; Res [type] = {str} // If the verification returns NULL otherwise returns an object (including our custom properties) Return ValidateRex.test (str)? Null: res;}}  

Let’s import this function in your code.:

Import {ValidateRex} from ‘./validate-register’;
Modify the validationMessage property To:
/ / For each table verification Add Description text validationMessage = {'username': {'minlength': 'username length is at least 3 characters 'Maxlength': 'User name length is 10 characters',' Required ':' Please fill in the username ',' NOTDOWN ':' Username You can not follow the underscore ',' Only ':' username can only include Digital, letters, underlined '}};
Modified BuildForm method:

// builds a form this THIS through the FormBuilder .registerform = this.fb.group ({/ * to add 5 authentication rules for username: * 1. Required, 2. Maximum length is 10, 3. The minimum length is 3, 4. Do not start with the underside, 5. only Can contain numbers, letters, underline * where the first empty string parameter is the default value of the form * / ‘username’: [‘”, [Validators.Required, Validators.maxlength (10), Validators.minlength (3), ValidateRex (‘notdown’, / ^ (?! _) /), validaterex (‘only’, / ^ [1-9A-zA-z _] + $ /)]]});
  OK! Datual, hurry to run the code, we can add various verification rules at any time, just modify the validationMessage property and the buildform method!  
If you add a plurality of form controls, you also need to modify the FormerRors, such as adding the Password control, modifying formerroRRORS for


forMerrorS = {username: ‘ ‘, password:’ ‘};


Everyone can try it!
   register.component.html 


Registration

User Name:
   {formerroS.UserName}} 

   
Form {Width: 90%; Max-Width: 45em; margin: auto;} .showerr {White-Space: Pre / WHITE: Pre -wrap;}

register.component.ts:

 Import {company, oninit} from'@ Angular / core'; import {FormBuilder, FormGroup, Validators} from '@ angular / forms'; import {validateRex} from './validate-register'; @Component ({selector: 'app-register', templateUrl: './register.component.html', Styleurls: ['./register.component.css']}) Export Class RegisterComponent Implements OnNInit {// Define Form RegisterForm: FormGroup; // Form Verification The error message displayed when not passed FORMERRORS = {Username: ''}; // For each form verification Add instructions text validationMessage = {'username': {'minlength': 'username length is 3 characters',' maxlength ':' username The length is up to 10 characters', 'Required': 'Please fill in the username', 'NOTDOWN': 'Username You cannot follow the underscore', 'Only': 'username can only contain numbers, letters, underlined'}} ; // Add a FB property to create a form constructor (private fb: formbuilder) {} ngoninit () {// initialization, build form this.buildform ();} // build table unilateral method buildform (): void {//// Build a form T by FormBuilderhis.registerform = this.fb.group ({/ * Add 3 verification rules for username: * 1. Required, 2. Maximum length is 10, 3. The minimum length is 3, 4. Do not open the next line, 5. Can only include numbers, letters, underline * where the first empty string parameter is the default value of the form * / 'username': [', [Validators.Required, Validators.Maxlength (10), Validators.MinLength (3) , ValidateRex ('NOTDOWN', / ^ (?! _) /), ValidateRex ('Only', / ^ [1-9A-ZA-z_] + $ /)]]}); // Each table data occurs Update error information this.registerform.valuechanges .Registerform.ValueChanges .Subscribe (Data => this.onValueChanged (data)); // Initialization Error message this.onValueChanged ();} // Trigger this method onValueChanged when data changes Data ?: any) {// If the form does not exist, return if (! this.register) return; // Get the current form const form = this.registerform; // Traverse Error message object for (Const Field in this.formerro ) {// Empty Current Error Message this.formerrors [Field] = ''; // Gets Control = Form.Get (Field) of the current form; // Current formPresence This Space Control & This Control is not modified && This control does not pass if (Control && Control.dirty &&! Control.valid) {// Get the verified control name, in order to get more detailed information Const Messages = this.validationMessage [field]; // Traverse the error object of the current control, get the attribute for the validation does not pass all the verification does not pass the instructions of the instructions to the wrong message this . formerrors [Field] + = Messages [Key] + '\ n';}}}}}   
Validate-Register.ts:


import {ValidatorFn, AbstractControl} from ‘@ angular / forms’; export function validateRex (type: string, validateRex: RegExp): ValidatorFn {return (control: AbstractControl): {[key: string] : any} => {// Get the contents of the current control const str = control.value; // Set our custom sever type const res = {}; res [type] = {str} // If the verification passes NULL Otherwise returns an object (contains our custom properties) Return ValidateEx.test (str)? Null:}}}
 The above is all the contents of this article, I hope that everyone's learning is helpful, I hope that everyone will support Tumi Clouds.   
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment