前端各种表单校验规则JavaScript/TypeScript实现 

前端各种表单校验规则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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值