Home > Web Front-end > JS Tutorial > body text

Detailed explanation of form verification steps in angular4

php中世界最好的语言
Release: 2018-04-17 14:25:30
Original
1626 people have browsed it

This time I will bring you a detailed explanation of the steps for form verification in angular4. What are the precautions for angular4 about form verification? Here are practical cases, let’s take a look.

This chapter introduces the creation of responsive forms and verification of form input values. We will skip the template forms.

1. Steps to use responsive forms

1. Introduce ReactiveFormsModule
in the module (usually app.module.ts) 2. Use responsive form

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
export class ReactiveFormComponent implements OnInit {
  private myForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }
  ngOnInit() {
  }
  // 创建表单元素
  createForm() {
    this.myForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
      mobile: ['', [Validators.required]],
      password: this.fb.group({
        pass1: [''],
        pass2: ['']
      })
    });
  }
  // 提交表单函数
  postDate() {
    /**
     * valid:是否有效
     * invalid:无效
     * dirty:脏
     * status:状态
     * errors:显示错误
     */
    if(this.myForm.valid){
      console.log(this.myForm.value);
    }
  }
}
Copy after login

in the component’s ts file 3. Use

<form [formGroup]="myForm" (ngSubmit)="postDate()">
  <p class="form-group">
    <label for="username">用户名:</label>
    <input type="text" placeholder="请输入用户名" class="form-control" id="username" formControlName="username" />
  </p>
  <p class="form-group">
    <label for="mobile">手机号码:</label>
    <input type="text" placeholder="请输入手机号码" class="form-control" id="mobile" formControlName="mobile"/>
  </p>
  <p formGroupName="password" style="border:none;">
    <p class="form-group">
      <label>密码:</label>
      <input type="password" class="form-control" placeholder="请输入密码" formControlName="pass1" />
    </p>
    <p class="form-group">
      <label>确认密码:</label>
      <input type="password" class="form-control" placeholder="请再次输入密码" formControlName="pass2" />
    </p>
  </p>
  <p class="form-group">
    <input type="submit" value="提交" class="btn btn-warning" [disabled]="!myForm.valid" />
  </p>
</form>
Copy after login

in the html page of the component 2. Use the form to verify data

1. Angular comes with three common form verifications: required, minLength, maxLength
in Validators. 2. Custom form validator (actually just a function, parameters of function is the current row that needs to be verified, and returns an arbitrary object)

**格式**
export function fnName(control:FormControl|FormGroup):any{
}
Copy after login

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

3. Steps to customize a verification method

1. Write the validator needed in the project into a separate file

import { FormControl, FormGroup } from '@angular/forms';
/**
 * 自定义验证器(其实就是一个函数,一个返回任意对象的函数)
 * 传递的参数是当前需要验证的表单的FormControl
 * 通过传递的参数获取当前表单输入的值
 */
export function mobileValidator(control: FormControl): any {
  console.dir(control);
  // 获取到输入框的值
  const val = control.value;
  // 手机号码正则
  const mobieReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
  const result = mobieReg.test(val);
  return result ? null : { mobile: { info: '手机号码格式不正确' } };
}
Copy after login

2. Use your own defined validator

createForm() {
  this.myForm = this.fb.group({
    username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
    mobile: ['', [Validators.required, mobileValidator]],
    password: this.fb.group({
      pass1: [''],
      pass2: ['']
    })
  });
}
Copy after login

3. Define the verification of a cipher group

// 定义一个密码组的验证方法
export function passValidator(controlGroup: FormGroup): any {
  // 获取密码输入框的值
  const pass1 = controlGroup.get('pass1').value as FormControl;
  const pass2 = controlGroup.get('pass2').value as FormControl;
  console.log('你输入的值:', pass1, pass2);
  const isEqule: boolean = (pass1 === pass2);
  return isEqule ? null : { passValidator: { info: '两次密码不一致' } };
}
Copy after login

4. Use

createForm() {
  this.myForm = this.fb.group({
    username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
    mobile: ['', [Validators.required, mobileValidator]],
    password: this.fb.group({
      pass1: [''],
      pass2: ['']
    }, {validator: passValidator})
  });
}
Copy after login

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

1. The page displays error

<p class="form-group">
  <label for="username">用户名:</label>
  <input type="text" placeholder="请输入用户名" class="form-control" id="username" formControlName="username" />
  <!-- 当输入框没有访问的时候或者合法的时候不显示 -->
  <p [hidden]="myForm.get(&#39;username&#39;).valid || myForm.get(&#39;username&#39;).untouched">
    <p [hidden]="!myForm.hasError(&#39;required&#39;,&#39;username&#39;)">用户名必填的</p>
    <p [hidden]="!myForm.hasError(&#39;minlength&#39;,&#39;username&#39;)">用户名长度过短</p>
    <p [hidden]="!myForm.hasError(&#39;maxlength&#39;,&#39;username&#39;)">用户名长度太长</p>
  </p>
</p>
<p class="form-group">
  <label for="mobile">手机号码:</label>
  <input type="text" placeholder="请输入手机号码" class="form-control" id="mobile" formControlName="mobile"/>
  <p [hidden]="myForm.get(&#39;mobile&#39;).valid || myForm.get(&#39;mobile&#39;).untouched">
    <p [hidden]="!myForm.hasError(&#39;mobile&#39;, &#39;mobile&#39;)">{{myForm.getError('mobile', 'mobile')?.info}}</p>
  </p>
</p>
<p formGroupName="password" style="border:none;">
  <p class="form-group">
    <label>密码:</label>
    <input type="password" class="form-control" placeholder="请输入密码" formControlName="pass1" />
  </p>
  <p class="form-group">
    <label>确认密码:</label>
    <input type="password" class="form-control" placeholder="请再次输入密码" formControlName="pass2" />
  </p>
  <!-- 对于group可以不在外面加一层判断 -->
  <p>
    <p [hidden]="!myForm.hasError(&#39;passValidator&#39;,&#39;password&#39;)">
      {{myForm.getError('passValidator','password')?.info}}
    </p>
  </p>
</p>
Copy after login

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;
}
Copy after login

5. Custom class display error

1. Write

in the input box If it means that the field is invalid and has been touched, add this class="error"

 [class.error]="myForm.get('username').invalid && myForm.get('username').touched"
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to use the computed attribute in Vue

Detailed explanation of the use of native ajax get and post methods

The above is the detailed content of Detailed explanation of form verification steps in angular4. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!