Home > Web Front-end > JS Tutorial > Custom validator for Reactive Form

Custom validator for Reactive Form

php中世界最好的语言
Release: 2018-03-19 16:25:56
Original
2172 people have browsed it

This time I will bring you Reactive Form’s custom validator, what are the precautions for using Reactive Form’s custom validator, as follows This is a practical case, let’s take a look at it.

This article will introduce the relevant content of Reactive Form in Angular (Angular2+), including:

  • Reactive Form creation method

  • How to use verification

  • Custom validator

Start the text below!

Reactive Form creation method

First we need to use FormBuilder to create a FormGroup, like this:

registerForm: FormGroup;
constructor(
    private fb: FormBuilder,
) {}
ngOnInit() {
  this.registerForm = this.fb.group({
    firstName: [''],
    lastName: [''],
  })
}
Copy after login

firstName and lastName above is chosen by you and represents the name of a form control.
Then the HTML page looks like this:

<form [formGroup]="registerForm" (ngSubmit)="handleSubmit(registerForm)">
  <label>FirstName:</label>
  <input formControlName="firstName">
  <label>LastName:</label>
  <input formControlName="lastName">
  <button type="submit">Submit</button>
</form>
Copy after login

This creates a very simple form!

How to use verification

The input items of the form often need to be verified, so how to verify it?
It's actually very simple. Angular has already written some commonly used validators for us. Just use it like this:

ngOnInit() {
  this.registerForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.pattern('[A-Za-z0-9]*')],
  })
}
Copy after login

You can use the "necessary" validator or regular expressions. You just need to Just pass in a regular expression. In addition, there are minLength and maxLength etc.
If a control requires multiple validators, you can put them in an array:

lastName: ['', [Validators.pattern('[A-Za-z0-9]*'), Validators.required]]
Copy after login

If you want to get some prompts when inputting, you can write your HTML like this:

<form [formGroup]="registerForm" (ngSubmit)="handleSubmit(registerForm)">
  <label>FirstName:</label>
  <input formControlName="firstName">
  <p *ngIf="registerForm.controls.firstName.touched && registerForm.controls.firstName.invalid">
    This field is required!
  </p>
  <label>LastName:</label>
  <input formControlName="lastName">
  <p *ngIf="registerForm.controls.lastName.hasError(&#39;pattern&#39;)">
    Invalid input!
  </p>
  <button type="submit" [disabled]="!registerForm.valid">Submit</button>
</form>
Copy after login

The first control will give a prompt when you "touch" it and it is empty; the second control will give a prompt when the input does not comply with the regular expression rules, hasErrorThe method can also pass in parameters such as required, minLength, which correspond to different validators; finally, when the input does not comply with the rules, the Submit button is disabled.

The several validators provided by Angular are often not enough in actual projects, so we need to customize validators to meet our business needs!

Custom validator

The validator is actually a method with return!
Now let's write a validator to verify whether the value of a URL input box conforms to the rules:

export function validateUrl(control: AbstractControl){
  if(control.value){
    if(!control.value.startsWith('www') || !control.value.includes('.io')){
      return {
        inValidUrl: true
      }
    }
  }
  return null;
}
Copy after login

We test whether the input value starts with "www" and contains ".io". Then use the same method as the validator provided by Angular:

this.registerForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', [Validators.pattern('[A-Za-z0-9]*'), Validators.required]],
    website: ['', validateUrl], // <---
})
Copy after login

Then, you can write your HTML like this so that you can get prompts when appropriate:

<label>Website:</label>
  <input formControlName="website">
    <p *ngIf="registerForm.controls.website.invalid">
    Url must starts with www and includes .io
  </p>
Copy after login

OK, that’s it for today. .

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:

JavaScript Optimizing DOM

##How to implement two-way data binding in WeChat applet

The above is the detailed content of Custom validator for Reactive Form. 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