Pass a dynamic parameter in reactive form custom validator - javascript

I would like to pass a variable as a parameter in a custom validator like this
newSimulation: new FormControl('', [uniqNameValidator(this.options)])
Then use it in my custom validator
export function uniqNameValidator(list: any): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const simulationFlatList = list.map(val => val.closingPeriodSimulationName)
return simulationFlatList.indexOf(control.value) > -1 ? { message: "simulation exists" } : null;
}
}
The issue with this is that this.options is always empty. I initialize it to [] but when user interacts with the form ( first field ) I update it to an array of string, I think that the custom validator does not recheck the value of this.options ?
In this case how to pass a variable in custom validator ?

this may work, bind the function to component newSimulation: new FormControl('', [uniqNameValidator.bind(this)]) then in the function you can access this.options

Related

bind global value into ValidationErrors in angular

i try to bind value into ValidationErrors.
i have this method:
isUniqueEmail(control: FormControl): ValidationErrors {
if (control.value != null) {
console.log(control.value)
if(control.value == this.foundEmail){
console.log("found one");
return {isUniqueEmail: true}
}else{
return null;
}
}
}
this method check if control.value (email typing) equal email stored in global variable this.foundEmail then we have duplicate email.
My problem is: i can retreive data from foundEmail in this method because this method is private.
this method is located inside export class exampleComponent implements OnInit.
Error: ERROR TypeError: Cannot read properties of undefined (reading 'foundEmail')
But i check i have data into foundEmail
The validator function gets called from the FormControl so its context is not bound to the class you're defining the method on. You need to manually bind isUniqueEmail() to this.
Two options:
Use bind() when defining the FormControl:
name: new FormControl("", [
this.isUniqueEmail.bind(this),
]),
Define your validator as arrow function:
isUniqueEmail = (control: FormControl) => {
if (control.value != null) {
console.log(control.value)
if(control.value == this.foundEmail){
console.log("found one");
return {isUniqueEmail: true}
}else{
return null;
}
}
}

Angular Form Control Dynamic Parameter

So I have a form that I need to add validators to and some of the controls are required only if a certain condition is matched by another control. What is a good way to do this. I originally made a custom validator function that I passed in a parameter to the function to determine if it should be required, but it keeps the original value of the parameter not matter if I update other controls in the form.
public static required(bookType: BookType, controlKey: string) {
return (control: AbstractControl): ValidationErrors | null => {
if(this.isRequired(bookType,controlKey)){
return !control.value? {required: true} : null
}
return null;
}
}
the form book type is originally DIGITAL and I change the book type to PRINT it stays DIGITAL.
This feels like it should stay a form-control validator since I am validating one value, not the group.
What would be the best way to make this work?
You need to implement a cross fields validator. So you will be able to play with values of these fields inside the validator function. Details: https://angular.io/guide/form-validation#cross-field-validation
const deliveryAddressRequiredValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const bookType = control.get('bookType');
const deliveryAddress = control.get('deliveryAddress');
if (bookType && deliveryAddress && bookType.value === 'PRINT' && Validators.required(deliveryAddress)) {
return { deliveryAddressRequired: true };
}
// no validation for book type DIGITAL
return null;
};
Usage:
this.form = this.formBuilder.group({
bookType: ['', [Validators.required]],
deliveryAddress: [''],
}, {validators: deliveryAddressRequiredValidator});
To display error in the template use: form.errors?.deliveryAddressRequiredValidator

not set ouput value in reactive form - angular9

I have a form and in this for I use the from array :
private InitialFrom(): void {
this.addElectricMoneyFG = this.fromBuilder.group({
locales: this.fromBuilder.array([])
})
}
and i have a component , that have output by this value :
<multi-language-data-form
[selectLanguage]="selectLanguage"
[fields]="fields"
sticy="true"
(formValue)="setValue($event)"
></multi-language-data-form>
and it return this value from output :
locales:
0:
languageId: 1
moreAccountInfo: "gh"
name: "ghgh"
1:
languageId: 2
moreAccountInfo: "gh"
name: "ghgh"
and when i want to update the form from that value it not set value from the locals :
setValue(value): void {
this.addElectricMoneyFG.patchValue({ ...value });
}
whats the problem ? how can i set the value from the form ???
You do not need to create a formBuilder inside the main formBuilder, you can just do this:
private InitialFrom(): void {
this.addElectricMoneyFG = this.formBuilder.group({
locales: []
})
}
To patch the value to the form, you can pass LanguageId from (formValue) event, then get the value with find, and patch desired value to the FormGroup.
To use patchValue method, you need to precise the form field as key of the object parameter you pass to patchValue(). for example here it's "locales"
setValue(languageId: number): void {
var getLocale = this.fields.find(x => x.languageId == languageId);
this.addElectricMoneyFG.patchValue({ locales: getLocale });
}

Passing parameters retrieved from api call to Custom Validator in FormBuilder

In the component, I use formBuilder for Angular Reactive Forms
I get the example code from this post
min = 10;
max = 20;
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl(null, [Validators.required]),
password: new FormControl(null, [Validators.required, Validators.maxLength(8)]),
age: new FormControl(null, [ageRangeValidator(this.min, this.max)])
});
}
The custom validation is defined in function ageRangeValidator
function ageRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
return { 'ageRange': true };
}
return null;
};
}
In case, min and max are got from api call. How can to pass them to function custom validator?
FormControl API provide setValidators method. Which you can use to set Validator dynamically. Inside subscribe call back you can call setValidators something like this:
Try this:
..subscribe((result)=>{
this.age.setValidators([ageRangeValidator(result.min,result.max)]);
this.loginForm.get('age').updateValueAndValidity();
})
Example
I prefer the answer of Chellappan, but if you are going to change the value of max and min along the live of app angular, another way is that the function validator belong to the component and bind to this
//this function IN the component
ageRangeValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined && (isNaN(control.value) ||
control.value < this.min ||control.value > this.max)
) {
return { ageRange: true };
}
return null;
};
}
//and when create the component
age: new FormControl(15, [this.ageRangeValidator().bind(this)]) //<--see the bind(this)

Typescript generics is rejected when specifying `keyof?

I have a generic method which is from the RXJS library (here simplified) :
function Subject<T>(t: T):T {
return t;
}
I also have an interface which declares my app values. (keys can be added)
interface IState {
key1: number;
key2: string;
}
And finally I have a Store which applies to the IState interface with actual values, via the generic function wrapper ( the generic function is an alias to the RXJS subject)
let Store : IState= Subject<IState>({
key1: void 0,
key2: void 0,
})
Ok so lets add 2 method for getting & setting from store :
Setting to store :
function set<T>(name: keyof IState, statePart: T) {
Store={
...Store,
[name]: statePart
};
Usage : set<string>("key1", "3");
This function works fine and allows me to only use valid keys which belongs to IState. No errors here.
But looking at the Select method :
(invocation should be like: )
let myVal:number = select<number>("key1");
Here is the method :
function select<T>(k: keyof IState): T {
return <T>Store[k]; // <-- error here
}
Type 'string | number' cannot be converted to type 'T'. Type
'number' is not comparable to type 'T'.
Question:
Why is that ? If I remove the keyof :
function select<T>(k): T {
return <T>Store[k];
}
Then it does compile , but it's not making any sense , Store is type of Istate and Istate contains keys of Istate
Why does it work without keyof and how can I fix my code so that select method will force to select only keys of Istate ?
ONLINE DEMO
The problem is that k can be any key of IState so there is no way to make sure that Store[k] is compatible with T. I would change the generic parameter to be the key, and type the result in relation to the field type:
function select<K extends keyof IState>(k: K): IState[K] {
return Store[k];
}
let myVal = select("key1"); // myval is number
Also set can be improved to not have explicit generic parameters, and to ensure the value passed to set is compatible with the field type:
function set<K extends keyof IState>(name: K, statePart: IState[K]) {
Store={
...Store,
[name]: statePart
}
}
set("key1", 3);
Edit
As mentioned in the comments, you can see the actual inferred types if you hover over the call (at least in vscode):
If you want to keep the explicit type parameters, although I do not recommend this as you can easily mismatch the field type and the call type you can use a type assertion through any:
function select3<T>(k: keyof IState): T {
return Store[k] as any;
}

Categories