SoFunction
Updated on 2025-04-08

Example of verification about form in angular4

This chapter introduces the creation of responsive forms and the verification of form input values, and omits the template forms.

1. Steps to use responsive forms

1. Introduce ReactiveFormsModule in modules (usually)
2. Use responsive forms in component's ts file

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
export class ReactiveFormComponent implements OnInit {
  private myForm: FormGroup;
  constructor(private fb: FormBuilder) {
    ();
  }

  ngOnInit() {
  }
  // Create form elements  createForm() {
     = ({
      username: ['', [, (3), (6)]],
      mobile: ['', []],
      password: ({
        pass1: [''],
        pass2: ['']
      })
    });
  }
  // Submit form function  postDate() {
    /**
      * valid: Is it valid?
      * invalid: invalid
      * dirty: dirty
      * status: status
      * errors: Display error
      */
    if(){
      ();
    }
  }
}

3. Use it in the html page of the component

<form [formGroup]="myForm" (ngSubmit)="postDate()">
  <div class="form-group">
    <label for="username">username:</label>
    <input type="text" placeholder="Please enter a username" class="form-control"  formControlName="username" />
  </div>
  <div class="form-group">
    <label for="mobile">phone number:</label>
    <input type="text" placeholder="Please enter your mobile phone number" class="form-control"  formControlName="mobile"/>
  </div>
  <div formGroupName="password" style="border:none;">
    <div class="form-group">
      <label>password:</label>
      <input type="password" class="form-control" placeholder="Please enter your password" formControlName="pass1" />
    </div>
    <div class="form-group">
      <label>确认password:</label>
      <input type="password" class="form-control" placeholder="Please enter your password again" formControlName="pass2" />
    </div>
  </div>
  <div class="form-group">
    <input type="submit" value="submit" class="btn btn-warning" [disabled]="!" />
  </div>
</form>

2. Use form to verify data

1. There are three common form verifications in angular: required, minLength, maxLength in Validators
2. Custom form verification device (in fact, it is just a function, the parameter of the function is the line that needs to be checked, and returns an arbitrary object)

**Format**
export function fnName(control:FormControl|FormGroup):any{

}

3. Three values ​​can be written in the responsive form field. The first one is returned to the page. The second parameter is the verifier (can be a group), and the third parameter is asynchronous verification (common to determine whether the mobile phone number is repeated if the user name is registered).

3. Steps to customize a verification method

1. Write a file separately for the verification device you need in the project

import { FormControl, FormGroup } from '@angular/forms';
/**
  * Custom validator (actually a function, a function that returns any object)
  * The passed parameter is the FormControl of the form currently required to be verified
  * Get the value of the current form input through the passed parameters
  */
export function mobileValidator(control: FormControl): any {
  (control);
  // Get the value of the input box  const val = ;
  // Mobile phone number regular  const mobieReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
  const result = (val);
  return result ? null : { mobile: { info: 'Mobile phone number format is incorrect' } };
}

2. Use your own defined checker

createForm() {
   = ({
    username: ['', [, (3), (6)]],
    mobile: ['', [, mobileValidator]],
    password: ({
      pass1: [''],
      pass2: ['']
    })
  });
}

3. Define verification of a password group

// Define a password group verification methodexport function passValidator(controlGroup: FormGroup): any {
  // Get the value of the password input box  const pass1 = ('pass1').value as FormControl;
  const pass2 = ('pass2').value as FormControl;
  ('The value you entered:', pass1, pass2);
  const isEqule: boolean = (pass1 === pass2);
  return isEqule ? null : { passValidator: { info: 'The password is inconsistent twice' } };
}
 

4. Use

createForm() {
   = ({
    username: ['', [, (3), (6)]],
    mobile: ['', [, mobileValidator]],
    password: ({
      pass1: [''],
      pass2: ['']
    }, {validator: passValidator})
  });
}

4. About the display of errors in the front-end page

1. Page display error

<div class="form-group">
  <label for="username">username:</label>
  <input type="text" placeholder="Please enter a username" class="form-control"  formControlName="username" />
  <!-- When the input box is not accessed or legal -->
  <div [hidden]="('username').valid || ('username').untouched">
    <p [hidden]="!('required','username')">username必填的</p>
    <p [hidden]="!('minlength','username')">username长度过短</p>
    <p [hidden]="!('maxlength','username')">username长度太长</p>
  </div>
</div>
<div class="form-group">
  <label for="mobile">phone number:</label>
  <input type="text" placeholder="Please enter your mobile phone number" class="form-control"  formControlName="mobile"/>
  <div [hidden]="('mobile').valid || ('mobile').untouched">
    <p [hidden]="!('mobile', 'mobile')">{{('mobile', 'mobile')?.info}}</p>
  </div>
</div>
<div formGroupName="password" style="border:none;">
  <div class="form-group">
    <label>password:</label>
    <input type="password" class="form-control" placeholder="Please enter your password" formControlName="pass1" />
  </div>
  <div class="form-group">
    <label>确认password:</label>
    <input type="password" class="form-control" placeholder="Please enter your password again" formControlName="pass2" />
  </div>
  <!-- forgroupYou can do not add a layer of judgment outside -->
  <div>
    <p [hidden]="!('passValidator','password')">
      {{('passValidator','password')?.info}}
    </p>
  </div>
</div>

2. Define style files

.ng-touched:not(form),.ng-invalid:not(form) {
  border: 1px solid #f00;
}

.ng-valid:not(form),.ng-untouched:not(form) {
  border: 1px solid #ddd;
}
p{
  color:#f00;
}

5. Custom class display error

1. Write on the input input box

It means that the field is invalid and touched, add this class="error"

 []="('username').invalid && ('username').touched"

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.