简体   繁体   中英

How to validate Radio Buttons using ReactiveFormsModule in angularJS2?

i am new to angularJS2, I am trying to learn validation in angularJS2 form using ReactiveFormsModule. Now i am stuck on how to validate a Radio button in angularJS2

This is my Component code

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { userDetails } from '../app/userDetails'

@Component({
    selector: 'user-validation',
    templateUrl: '../app/app.template.html'
})
export class userComponent implements OnInit {
    constructor(private fb: FormBuilder) { }
    userForm: FormGroup;
    users = new userDetails();
    ngOnInit(): void {
        this.buildForm();
    }

    buildForm(): void {
        this.userForm = this.fb.group({
            'username': [this.users.username, [
                Validators.required,
                Validators.minLength(4),
                Validators.maxLength(24)
            ]
            ]
        });

        this.userForm.valueChanges
            .subscribe(data => this.onValueChanged(data));

        this.onValueChanged(); // (re)set validation messages now
    }
    onValueChanged(data?: any) {
        if (!this.userForm) { return; }
        const form = this.userForm;

        for (const field in this.formErrors) {
            // clear previous error message (if any)
            this.formErrors[field] = '';
            const control = form.get(field);

            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }
    onSubmit() {
        this.users = this.userForm.value;
    }
    formErrors = {
        'username': ''        
    };

    validationMessages = {
        'username': {
            'required': 'Name is required.',
            'minlength': 'Name must be at least 4 characters long.',
            'maxlength': 'Name cannot be more than 24 characters long.',
            'forbiddenName': 'Someone named "Bob" cannot be a hero.'
        }
    };
}

HTML code

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-group">
    <label>Gender</label>  
        <label><input type="radio" name="gender" /> Male</label> 
        <label><input type="radio" name="gender" />Female</label>
        <button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>
</form>

I am not able to find any document related to radio button validation in angularJS2, even here angular.io

base on your code, you could use like that.

this.userForm = this.fb.group({
  'username': [this.users.username, [
     Validators.required,
     Validators.minLength(4),
     Validators.maxLength(24)
   ]],
  'gender': [this.users.gender, Validators.required]
});

HTML template:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-group">
  <label>Gender</label>  
  <label><input type="radio" formControlName="gender" value="M" /> Male</label> 
  <label><input type="radio" formControlName="gender" value="F" />Female</label>
  <button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>
</form>

Please go through following link it will definately help you. https://github.com/angular/angular/issues/7282

Try to add following code into your Component code

this.userForm = this.fb.group({
  'username': [this.users.username, [
     Validators.required,
     Validators.minLength(4),
     Validators.maxLength(24)
   ]],
  'gender': [this.users.gender, Validators.required]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM