mirror of https://github.com/abpframework/abp.git
4 changed files with 71 additions and 0 deletions
@ -0,0 +1,37 @@ |
|||
import { FormControl } from '@angular/forms'; |
|||
import { validateRequired } from '../validators/required.validator'; |
|||
|
|||
describe('Validators', () => { |
|||
describe('Required Validator', () => { |
|||
const error = { required: true }; |
|||
|
|||
test.each` |
|||
input | options | expected |
|||
${0} | ${undefined} | ${null} |
|||
${false} | ${undefined} | ${null} |
|||
${null} | ${undefined} | ${error} |
|||
${undefined} | ${undefined} | ${error} |
|||
${''} | ${undefined} | ${error} |
|||
${''} | ${{}} | ${error} |
|||
${''} | ${{ allowEmptyStrings: false }} | ${error} |
|||
${''} | ${{ allowEmptyStrings: true }} | ${null} |
|||
`(
|
|||
'should return $expected when input is $input and options are $options', |
|||
({ input, options, expected }) => { |
|||
const control = new FormControl(input, [validateRequired(options)]); |
|||
control.markAsDirty({ onlySelf: true }); |
|||
control.updateValueAndValidity({ onlySelf: true, emitEvent: false }); |
|||
|
|||
expect(control.errors).toEqual(expected); |
|||
}, |
|||
); |
|||
|
|||
it('should return null when control is pristine', () => { |
|||
const invalidUrl = ''; |
|||
const control = new FormControl(invalidUrl, [validateRequired()]); |
|||
// control is not dirty
|
|||
|
|||
expect(control.valid).toBe(true); |
|||
}); |
|||
}); |
|||
}); |
|||
@ -0,0 +1,8 @@ |
|||
import { Validators } from '@angular/forms'; |
|||
import { validateRequired } from './required.validator'; |
|||
export * from './required.validator'; |
|||
|
|||
export const AbpValidators = { |
|||
email: () => Validators.email, |
|||
required: validateRequired, |
|||
}; |
|||
@ -0,0 +1,25 @@ |
|||
import { AbstractControl, ValidatorFn } from '@angular/forms'; |
|||
|
|||
export interface RequiredError { |
|||
required: true; |
|||
} |
|||
|
|||
export interface RequiredOptions { |
|||
allowEmptyStrings?: boolean; |
|||
} |
|||
|
|||
export function validateRequired({ allowEmptyStrings }: RequiredOptions = {}): ValidatorFn { |
|||
return (control: AbstractControl): RequiredError | null => { |
|||
return control.pristine || isValidRequired(control.value, allowEmptyStrings) |
|||
? null |
|||
: { required: true }; |
|||
}; |
|||
} |
|||
|
|||
function isValidRequired(value: any, allowEmptyStrings: boolean): boolean { |
|||
if (value || value === 0 || value === false) return true; |
|||
|
|||
if (allowEmptyStrings && value === '') return true; |
|||
|
|||
return false; |
|||
} |
|||
Loading…
Reference in new issue