parent
b2dd0f7a5c
commit
3ad0e4032e
@ -0,0 +1,65 @@ |
||||
import {AbstractControl, ValidationErrors, ValidatorFn, Validators} from '@angular/forms'; |
||||
import {NzSafeAny} from 'ng-zorro-antd/core/types'; |
||||
|
||||
export type validatorsErrorsOptions = { 'zh-cn': string; en: string } & Record<string, NzSafeAny>; |
||||
export type validatorsErrors = Record<string, validatorsErrorsOptions>; |
||||
|
||||
export class ValidatorsService extends Validators { |
||||
|
||||
/** |
||||
* 验证字符最小长度 |
||||
* @param minLength |
||||
*/ |
||||
static override minLength(minLength: number): ValidatorFn { |
||||
return (control: AbstractControl): validatorsErrors | null => { |
||||
if (Validators.minLength(minLength)(control) === null) { |
||||
return null; |
||||
} |
||||
return { minlength: { 'zh-cn': `最小长度为 ${minLength}`, en: `MinLength is ${minLength}` } }; |
||||
}; |
||||
} |
||||
|
||||
/** |
||||
* 验证字符最大长度 |
||||
* @param maxLength |
||||
*/ |
||||
static override maxLength(maxLength: number): ValidatorFn { |
||||
return (control: AbstractControl): validatorsErrors | null => { |
||||
if (Validators.maxLength(maxLength)(control) === null) { |
||||
return null; |
||||
} |
||||
return { maxlength: { 'zh-cn': `最大长度为 ${maxLength}`, en: `MaxLength is ${maxLength}` } }; |
||||
}; |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
/** |
||||
* 验证手机号 |
||||
* @param control |
||||
*/ |
||||
static mobile(control: AbstractControl): validatorsErrors | null { |
||||
const value = control.value; |
||||
|
||||
if (isEmptyInputValue(value)) { |
||||
return null; |
||||
} |
||||
|
||||
return isMobile(value) ? null : { mobile: { 'zh-cn': `手机号码格式不正确`, en: `Mobile phone number is not valid` } }; |
||||
} |
||||
|
||||
static isMobile(value: string): boolean { |
||||
return typeof value === 'string' && /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/.test(value); |
||||
} |
||||
|
||||
} |
||||
|
||||
|
||||
function isEmptyInputValue(value: NzSafeAny): boolean { |
||||
return value == null || value.length === 0; |
||||
} |
||||
|
||||
function isMobile(value: string): boolean { |
||||
return typeof value === 'string' && /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/.test(value); |
||||
} |
Loading…
Reference in new issue