Ionic 如何使用不同的API调用为多个字段创建正式的验证?

lp0sw83n  于 2023-11-15  发布在  Ionic
关注(0)|答案(1)|浏览(164)

我想用不同的API调用来验证多个formly字段,而不需要为每个场景创建自定义验证器。例如,在同一表单中,调用API/bankaccount-check,API/username-check来检查用户名字段和银行号码字段。

ippsafx7

ippsafx71#

因此,我将为多个字段创建一个formly验证实现。(在模块提供程序中设置)。这是因为JavaScript调用。验证有一个反跳,以防止不必要的调用服务器。调用的链接可以在JSON供电的表单中设置(见例子)。如果服务器回复一个data.error,这个错误将被用作验证消息(我将使用ionic)。每一个新的按键都会在反跳时间之后调用。所以用户输入有一个实时反馈。


的数据
我希望有人能从这个方法中受益。欢迎提出优化建议。

import { formService } from "src/app/services/form/form.service";
import { debounceTime, switchMap, map, first, distinctUntilChanged } from "rxjs/operators";
import { of } from "rxjs";
import { FormControl } from "@angular/forms";
import { FieldTypeConfig } from "@ngx-formly/core";

export function apiValidationFunction(FS: formService) {
    return {
        validators: [
            {
                name: "apiValidation",
                validation: (control: FormControl, field: FieldTypeConfig ) => {

                    if (!control.value || !field?.templateOptions?.validation?.url) {
                        return of(null);
                    }
                    const url = field?.templateOptions?.validation?.url;

                    return control.valueChanges.pipe(
                        debounceTime(field?.templateOptions?.validation?.debounce || 1000), // Adjust the debounce time as needed
                        distinctUntilChanged(),
                        switchMap((value) => FS.validationCall(url + value)),
                        map((result) => {
                            control.markAsTouched();
                            if (result && result["data"]["error"] !== "") {
                                control.setErrors({ apiValidation: {
                                    message: result["data"]["error"]
                                } });
                                return false;
                            } else {
                                return true;
                            }
                        }),
                        first((result) => result === true),
                    );
                },
            },
        ]
    };
}

字符串
表单模块看起来像这样。

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { IonicModule } from "@ionic/angular";
import { ReactiveFormsModule } from "@angular/forms";
import { AppFormlyConfig } from "./../../services/form/formly-config.service";
/** Formly */
import { FormlyModule, FormlyConfig,FORMLY_CONFIG} from "@ngx-formly/core";
import { FormlyIonicModule } from "@ngx-formly/ionic";
/** Validation */
import{ apiValidationFunction } from "./validators/api.validator";
import { FormService } from "src/app/services/form/form.service";

@NgModule({
    imports: [
        CommonModule,
        IonicModule,
        ReactiveFormsModule,
        FormlyModule.forRoot({
            validationMessages: [
                { name: "required", message: "Field is required" },
            ],
        }),
        FormlyIonicModule,
    ],
    declarations: [],
    providers: [
        { provide: FormlyConfig, useClass: AppFormlyConfig },
        {
            provide: FORMLY_CONFIG,
            multi: true,
            useFactory: apiValidationFunction,
            deps: [FormService],
        },
    ],
})
export class FormPageModule {}


要在json powerd表单中使用它,你可以这样使用它:

'fields' => [
            [
                'key' => 'username',
                'type' => 'input',
                'templateOptions' => [
                    'label' => 'Username',
                    'required' => true,
                    'validation' => [
                        'url' => "https://example.com/api/username-check?username=",
                        'debounce' => 800,
                    ],
                ],
                "asyncValidators" => [
                    "validation" => [ 'apiValidation'],
                ]
            ],
            [
                'key' => 'bankaccount',
                'type' => 'input',
                'templateOptions' => [
                    'label' => 'Bankaccount',
                    'required' => true,
                    'validation' => [
                        'url' => "https://example.com/api/bankaccount-check?number=",
                        'debounce' => 800,
                    ],
                ],
                "asyncValidators" => [
                    "validation" => [ 'apiValidation'],
                ]
            ],
        ]


表单服务看起来像这样:

import { Injectable } from "@angular/core";
import { HttpHeaders, HttpClient } from "@angular/common/http";

export const HEADER = {
    headers: new HttpHeaders({
        "Content-Type": "undefined",
    }),
};

@Injectable({
    providedIn: "root",
})
export class FormService {
    passedData: any;

    constructor(private http: HttpClient) {}

    public validationCall(url: string) {
        return this.http.post(url, { headers: HEADER.headers })
    }
}

相关问题