我该如何进行表单验证?

时间:2018-06-29 15:27:38

标签: angular forms validation

我的表单包含以下元素:

  • 名字
  • 姓氏
  • 用户ID
  • 参考号
  • 资产标签
  • 从日期起
  • 迄今为止

我正在尝试对表单进行验证,以便满足以下规则时表单将enable提交按钮。

  • 必须始终有一个起始日期和起始日期。
  • 必须至少具有以下一项
    • 姓氏名字
    • 用户ID
    • 参考号码
    • 资产标签

我使用formGroup构建表单,如下所示:

this.searchForm = this.fb.group({
    criteria: this.fb.group({
        name: this.fb.group({
            firstName: [{ value: null, disabled: false }, [
                Validators.pattern(new RegExp('[A-Za-z]'))
            ]],
            lastName: [{ value: null, disabled: false }, [
                Validators.pattern(new RegExp('[A-Za-z]'))
            ]],
        }, { validator: atLeastOneName }),
        userId: [{ value: null, disabled: false }, [
            Validators.minLength(8),
            Validators.maxLength(8)
        ]],
        refNumber: [{ value: null, disabled: false }, [
            Validators.minLength(7),
            Validators.maxLength(7)
        ]],
        assetTag: [{ value: null, disabled: false }, [
            Validators.minLength(9),
            Validators.maxLength(9)
        ]],
    }, { validator: atLeastOne }),
    fromDate: [moment().subtract(30, 'days').format('MM/DD/YYYY'), [
        Validators.required
    ]],
    toDate: [moment().format('MM/DD/YYYY'), [
        Validators.required
    ]]
}, { validator: hasValidDates });

我的验证者就是这样

export function atLeastOne(form: FormGroup): ValidationErrors {
    const message = {
        'search': {
            'message': 'At least one field should be entered for the search'
        }
    };

    let hasValues = false;

    Object.keys(form.value).map(k => {
        if (form.value[k] !== '' && form.value[k] !== null) { hasValues = true; }
    });

    console.log('hasValues: ', hasValues);

    return hasValues ? null : message;
}

export function atLeastOneName(form: FormGroup): ValidationErrors {
    const message = {
        'search': {
            'message': 'At least one name must be present for the search'
        }
    };

    let hasNames = false;

    let firstName = form.value['firstName'],
        lastName = form.value['lastName'];

    if (firstName && lastName) {
        hasNames = true;
    } else if (!firstName && !lastName) {
        hasNames = true;
    } else {
        hasNames = false;
    }

    console.log('hasNames: ', hasNames);

    return hasNames ? null : message;
}

export function hasValidDates(form: FormGroup): ValidationErrors {
    const message = {
        'search': {
            'message': 'Your input dates are invalid, please double check them.'
        }
    };

    let validDates = false;

    let fromDate = form.controls['fromDate'],
        toDate = form.controls['toDate'];

    if (new Date(fromDate.value) <= new Date(toDate.value)) {
        validDates = true;
    }

    let momentFromDate = moment(fromDate.value),
        momentToDate = moment(toDate.value);
    if (momentFromDate.diff(momentToDate, 'months') > 6) {
        validDates = false;
        message.search.message = 'Please restrict your input dates to less than a 6 month period.';
    }

    return validDates ? null : message;
}

但是;使用此当前结构,页面加载时将启用表单。这是不希望的,因为名字,姓氏,用户ID,参考编号或资产标签没有 no 值。我觉得有一种更清洁的方法。

0 个答案:

没有答案