前端各种表单校验规则Typescript实现
import { Injectable } from '@angular/core';
import { FormControl, AbstractControl, ValidatorFn } from '@angular/forms';
import { isIPv4, isIPv6 } from './ip';
const is: any = (window as any).is;
const REGEXES = {
positiveInt: /^[1-9]\d*$/,
filePath: /^([\/]{0,1}[A-Za-z0-9\_]+)+$/,
ipv4: /^(?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/,
ipv6: /^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i,
url: /^((http[s]{0,1}|ftp):\/\/){0,1}((([0-9]{1,3}\.){3}[0-9]{1,3})|([a-zA-Z0-9\.\-]+\.([a-zA-Z]{2,6})))(:\d+)?(\/[a-zA-Z0-9\-~!@#$%^&*+?:_\/=<>\.]*)?$/i, // 有无协议均可且无文件
email: /^[a-zA-Z0-9]([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+([\.][a-zA-Z0-9]+)*[\.][a-zA-Z]{2,3}([\.][a-zA-Z]{2})?$/
};
@Injectable({
providedIn: "root"
})
export class ValidatorService {
constructor() { }
static specialcode(control: FormControl): { [prop: string]: {} } {
if (!control.value) {
return;
}
const special = /[#"^@/%|=;<>:'\\]/;
if (special.test(control.value)) {
return { specialcode: '#"^@/%|=;<>:\'\\' };
}
}
// 特殊字符 -- #^@/>
static specialcodeConfig(control: FormControl): { [prop: string]: {} } {
if (!control.value) {
return;
}
const special = /[#^@/>]/;
if (special.test(control.value)) {
return { specialcode: '#^@/>' };
}
}
// 校验手机号
static phonenumber(control: FormControl): { [prop: string]: {} } {
if (!control.value) {
return;
}
const reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
if (!reg.test(control.value)) {
return { phonenumber: '请输入合法手机号' };
}
}
// 数据源端口
static port(control: FormControl): { [prop: string]: boolean } {
if (!control.value) {
return;
}
if (
!(
REGEXES.positiveInt.test(control.value) &&
Number(control.value) > 0 &a