How to use input type hidden in Angular FormBuilder? - angular-reactive-forms

I am running an application using Angular CLI 9.0.7. In this application I use FormBuilder to with two input fields of type hidden. When I run the application I get the message:
Error: Cannot find control with name: 'codigoIbgeMunicipioForm'
How can I do to use input hidden in my form?
This is my component source code where I defined the input hidden fields.
private adicionarEnderecoFormGroup(): FormGroup {
return this.formBuilder.group({
cepForm: ['', [Validators.required, CepValidator.cepValido]],
numeroEnderecoForm: ['', Validators.required],
complementoForm: [''],
tipoLogradouroForm: ['', Validators.required],
logradouroForm: ['', Validators.required],
bairroForm: ['', Validators.required],
cidadeForm: ['', Validators.required],
estadoEnderecoForm: ['', Validators.required],
codigoIbgeMunicipioForm: [''], // <- look the field id defined here
paisForm: ['BR'], // <- this field is hidden type too
}, { validators: LojistaEnderecoValidator.enderecoDuplicado(this.enderecos) });
}
And this my Html file
<div FormGroupName="enderecoFormGroup">
<input formControlName="codigoIbgeMunicipioForm" id="codigoIbgeMunicipioForm" type="hidden" />
<input formControlName="paisForm" id="paisForm" type="hidden" />

I didn't find what was wrong, so I removed the component from the project, created the component again, pasted the code back, compiled and it worked ...
Strange, but it worked.

Related

Vue component, prop is declared and passed, but console says prop is missing

I'm working on creating reusable form inputs using vue + laravel.
I have one prop that is required, and I pass it and it renders as expected, but the console still logs the error:
"Vue warn]: Missing required prop: "inputId"".
Inspecting the vue element shows the prop as defined. Why is an error being generated while the the data is being passed?
Text Input Component
<template>
<input type="text" :name="inputId" :id="cssid" :placeholder="placeholder" :value="value">
</template>
<script>
export default {
props: {
inputId: {
type: String,
required: true,
},
isRequired: {
type: Boolean,
default: false,
},
placeholder: {
type: String,
},
value: {
type: String,
default: '',
},
},
mounted() {
console.log('text mounted.')
},
computed: {
cssid() {
return this.inputId + '_selection';
},
},
}
</script>
Fragment of blade view where component is being called (I've tried with title in quotes and not in quotes, no difference)
<text-input
input-id="title"
></text-input>
Resultant html Result is correct, but why the error?
<input type="text" name="title" id="title_selection">
In this case, I had two instances of the component and I didn't realize the older one was there. The older one didn't have the prop declared and was giving the error, but it wasn't obvious in the console that I had loaded it twice. Removing the older instance of the component fixed the error.

Knockout JS Special characters validation

I'm trying to disable my user input so they cannot use special characters, I've tried looking for solutions but was unable to find any.
e.g I don't want my Clint to be able to enter the following characters in the input box: {{!##$%^&*()_+=}}
please help.
This is my current code
self.modelView = {
Id: ko.observable(),
Name: ko.observable().extend({
required: true,
minLength: 2,
maxLength: 25
}),
Address: ko.observable().extend({
required: true,
minLength: 2,
maxLength: 25
})
};
By the code, it looks as if you are using knockout-validation, and it supports html5 attribs:
<input type="text" data-bind="value: myProp" pattern="^[a-z0-9].*" />
The pattern-attrib will take an regular expression, to fit your requirements
Name: ko.observable().extend({
required: true,
pattern: ^[a-z0-9].*
});

Handling Angular2 - 4 errors with nested form groups in reactive forms

Guys I need some help with Angular 4 reactive forms. I have nested form-groups also works fine except Validation. But my app is crashing when I try to add some handling validation in my html markup.
my component code looks like:
createForm() {
let options: any = {};
for (let option of this.annoucementOptions) {
options[option.title] = new FormControl(false);
}
let optionsFormGroup: FormGroup = new FormGroup(options);
this.annoucementForm = this.fb.group({
address: this.fb.group({
country: ['', [Validators.maxLength(50)]],
state: ['', [Validators.maxLength(50)]],
city: ['', [Validators.required, Validators.maxLength(50)]],
street: ['', [Validators.required, Validators.maxLength(50)]],
apartment: ['', [Validators.required, Validators.maxLength(50)]],
}),
description: this.fb.group({
title: ['', [Validators.required, Validators.maxLength(80)]],
shortDescription: [''],
livingPlaces: [''],
room: [''],
options: optionsFormGroup
}),
priceBlock: this.fb.group({
price: ['', [Validators.required, Validators.maxLength(80)]],
type: ['', [Validators.required, Validators.maxLength(80)]],
}),
});
}
and this is a piece of my template code:
<form class="form form-lg form-def" *ngIf="annoucementForm" (ngSubmit)="saveDetails(annoucementForm)" name="annoucementForm" [formGroup]="annoucementForm">
<div class="form-block" formGroupName="address">
<h2 class="form-block-heading flag-label primary">Address</h2>
<ul class="row form-list">
<li class="col-md-6 col-lg-4 form-list-item">
<md-input-container class="d-block">
<input type="text" mdInput placeholder="*Country" formControlName="country">
</md-input-container>
<div class="form-error text-danger"
*ngIf="annoucementForm.get('country').touched "
>
<p *ngIf="annoucementForm.get('country').hasError('maxlength')">
*This field be more than 35 characters long.
</p>
</div>
</li>
</ul>
Use
annoucementForm.get('address.country')
or
annoucementForm.get(['address', 'country'])
instead of
annoucementForm.get('country')

Angular 2 force custom validation on keyup

I have this code:
this.form = fb.group({
username: ['', Validators.compose([Validators.required])],
fullName: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])],
confirmPassword: ['', Validators.required],
}, {validator: matchingPasswords('password', 'confirmPassword')});
matchingPasswords:
export function matchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
let password = group.controls[passwordKey];
let passwordConfirmation = group.controls[passwordConfirmationKey];
if (password.value !== passwordConfirmation.value) {
return passwordConfirmation.setErrors({mismatchedPasswords: true})
}
}
}
html:
<div class="form-group">
<input [formControl]="confirmPassword" class="form-control checking-field" type="password">
<span class="help-block text-danger" *ngIf="form.get('password').touched && form.get('password').hasError('required')">
</div>
<div class="form-group">
<input class="custom-control-input checkbox-main" type="checkbox" [(ngModel)]="policyButtonValue" [ngModelOptions]="{standalone: true}" ngDefaultControl>
<span class="custom-control-indicator"></span>
</div>
this is functional, and works perfectly, but I have a special use-case scenario that should be fixed.
click in the first password field.
fill up a password, eg.: "foo"
click in the confirm password field.
tpye in the same thing, eg.:"foo"
till this point, no problems.
type something different into the confirm password field, eg: "foobar"
(at this point, the validator shows that there is an error here)
click in the password field
type in the same thing that is in the password field: "foobar"
and here, the confirm password field is still invalid, until the password field looses focus...
is there a way, to force the matchingPassword validation run on keyup event, rather than how it works now?
You need an else block:
if (password.value !== passwordConfirmation.value) {
passwordConfirmation.setErrors({mismatchedPasswords: true})
}
else {
passwordConfirmation.setErrors(null);
}

Angular 2 MDF validator to require atleast one of two fields

I have two input fields: email and phone, if user enters input in email then phone input is not required and vice versa. Atleast one of the fields is required at a time. I have model driven form and I am trying to write a custom validator function for this. So far I have got:
In my validator.ts:
import { FormGroup, FormControl } from '#angular/forms';
export function requiredOptional(emailVal: string, phoneVal: string) {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailVal];
let phone = group.controls[phoneVal];
if (!email.value|| !phone.value) {
return {
isRequired: true
};
}
}
}
In my testForm.component.ts:
export class TestFormComponent{
testForm: FormGroup;
constructor(public fb: FormBuilder) {
this.testForm= fb.group({
email: ['', emailValidator],
phone: ['', phoneValidator],
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
}, {validator: matchingPasswords('password', 'confirmPassword')},
{validator: requiredOptional('email', 'phone')}
)
}
onSubmit(value: Object): void {
console.log(value);
}
}
and in my testForm.component.html:
<form [formGroup]="testForm" novalidate (ngSubmit)="testForm.valid && onSubmit(testForm.value)">
.......
<input type="email" placeholder="Email*" formControlName="email">
<div class="form-text error" *ngIf="testForm.controls.email.touched">
<div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
<div *ngIf="testForm.controls.email.hasError('invalidEmail')">Email is invalid.</div>
</div>
.......
<input type="text" placeholder="Mobile Number*" formControlName="phone">
<div class="form-text error" *ngIf="testForm.controls.phone.touched">
<div *ngIf="testForm.hasError('isRequired')">Email or Phone is required.</div>
<div *ngIf="testForm.controls.phone.hasError('invalidPhone')">Phone is invalid.</div>
</div>
.......
<button [disabled]="!testForm.valid" type="submit" class="btn btn-primary pull-right">Sign up</button>
</form>
But this is not working, I am getting error in testForm.component.ts: Supplied parameters do not match any signature of call targets
You can define multiple validating functions by composing like following:
export class TestFormComponent{
testForm: FormGroup;
constructor(public fb: FormBuilder) {
this.testForm= fb.group({
email: ['', emailValidator],
phone: ['', phoneValidator],
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
}, {validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]})
}
onSubmit(value: Object): void {
console.log(value);
}
}
Focus on following change:
{validator: Validators.compose([matchingPasswords('password', 'confirmPassword'), requiredOptional('email', 'phone')]}
Instead of setting matchingPasswords validator, we can set array of validating functions by using Validators.compose

Resources