Asked by:
Formvalidation if checkbox with value true is clicked

Question
-
User-1121540557 posted
Hi,
I have a Angular form where I need to at some validation.
Problem is that the user may only submit the form if the email and answer is correct.The answer is in a checkbbox array.. (value = true) the other two checkboxes have false value.
ts code:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, FormArray, FormControl, Validators, AbstractControl, ValidatorFn, ValidationErrors, NgModel } from '@angular/forms'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr' import { UserService } from "./../../services/user.service"; import { questionMode} from "./../../models/questionMode.model"; import { User } from "./../../models/user.model"; import { makeStyles } from '@material-ui/core/styles'; @Component({ selector: 'app-confirmquestion', templateUrl: './confirmquestion.component.html', styleUrls: [] }) export class ConfirmQuestionComponent implements OnInit { form: FormGroup; constructor( private userServive: UserService, private router: Router, private toastr: ToastrService, private fb: FormBuilder ) { } colorList: any[] = [ { names: ['blue', 'indigo', 'purple', 'pink', 'orange', 'red', 'yellow', 'green', 'teal', 'cyan', 'white', 'gray', 'gray-dark', 'black'], colors: ['#007bff', '#6610f2', '#6f42c1', '#e83e8c', '#fd7e14', '#fd7e14', '#ffc107', '#28a745', '#20c997', '#17a2b8', '#fff', '#6c757d', '#343a40', '#000'] } ] emailPattern: "^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$"; exampleDiv: any[] = []; colorDivs: any[] = []; colorNames: any[] = []; anwserNumber: number = 0; anwsers: boolean[] = []; answer: any[] = []; answerName: string; answerColors: any[] = []; answerColor: string; props: any; useStyles: any; ngOnInit() { this.getColors(); this.useStyles = makeStyles({ answerStyle: { height: '125px;', width: '125px;', backgroundColor: this.answerColor } }); this.form = this.fb.group({ email: new FormControl(['', [Validators.required, Validators.pattern(this.emailPattern)]]), answer: new FormControl(this.answer), checkArray: this.fb.array([], this.answerValidator ) }) this.form.status === 'INVALID'; } // also tried Validators.requiredTrue on the array but not working... get f() { return this.form.controls; } onCheckboxChange(e) {// <=== Not working const checkArray: FormArray = this.form.get('checkArray') as FormArray; if (e.target.checked) { var sValue: any = e.target.value; if (sValue == "true") { this.toastr.success('form is valid', 'the form is ready to send'); this.form.status === 'VALID';// <=== Not working } else { this.toastr.error('Invalid answer', 'Please try again.'); this.form.status === 'INVALID'; this.resetForm(); this.getColors(); } } } checkAnswer(res: any): boolean { if (this.answerName == res) { this.answer = []; this.answer.push({ value: "true" }); this.toastr.success('form is valid', 'the form is ready to send'); this.form.status === 'VALID'; return true; } else { this.toastr.error('incorrect answer', 'Try again.'); this.form.status === 'INVALID'; this.resetForm(); this.getColors(); return false; } } answerValidator(control: AbstractControl): { [key: string]: boolean } | null { // const answerValue = this.form.get('answer'); if (control.value !== undefined && (isNaN(control.value) || control.value == 'true')) { return { 'cAnwser': true }; } return null; } }
HTML
<form [formGroup]="form" (ngSubmit)="submitForm()"> <div class="form-group required"> <div class="md-form"> <input type="text" #email id="ipEmail" formControlName="email" required class="form-control" placeholder="Please add a valid emailaddress" autocomplete="email" [(ngModel)]="form.email"> <label class="text-danger" *ngIf="form.get('email').touched && form.get('email').errors?.required">Add a valid emailaddress.</label> <label class="text-danger" *ngIf="form.get('email').touched && form.get('email').errors?.email">invalid email address</label> </div> </div> <div class="form-group"> <div class="form-row col-lg-12"> <div class="col col-md-1"> <div style="height: 100px; width: 100px;"> <ul *ngFor="let color of answerColors; let j=index"> <div class="row"> <strong><label>{{answerName}}</label></strong> </div> <div class="row"> <div [style.background-color]="color" style="height: 60px; width: 60px;"> </div> </div> </ul> </div> </div> </div> </div> <div class="form-group" *ngFor="let data of colorDivs; let i=index"> <label> <input type="checkbox" [value]="data[0]['isAnswer']" name="dcolorNames" required (change)="onCheckboxChange($event)" /><strong>{{data[0]['name']}}</strong> </label> </div> <!-- validator also not working --> <p class="error" *ngIf="this.form.controls['checkArray'].errors?.required"> please supply one answer.. </p> <button mdbBtn class="btn form-btn-save-r text-center" outline="true" rounded="true" block="true" type="submit" [disabled]="form.invalid">Submit</button> </form>
Monday, February 17, 2020 11:43 PM
All replies
-
User-474980206 posted
as this is a pure angular question and nothing to do with asp.net / SPA interaction, you might try an angular support forum. google for angular support forums
Tuesday, March 17, 2020 8:13 PM