Skip to content

Commit e63d851

Browse files
committed
feat: support tel type validator
1 parent 4c33ac0 commit e63d851

2 files changed

Lines changed: 67 additions & 3 deletions

File tree

src/rule/type.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ const pattern = {
1313
// 'i',
1414
// ),
1515
/**
16-
* Phone number regex, support country code, brackets, spaces, dots, and dashes.
16+
* Phone number regex, support country code, brackets, spaces, and dashes (or non-breaking hyphen \u2011).
1717
* @see https://regexr.com/3c53v
1818
* @see https://ihateregex.io/expr/phone/
19+
* @see https://developers.google.com/style/phone-numbers using non-breaking hyphen \u2011
1920
*/
20-
tel: /^(\+[0-9]{1,3}[-\s\.]?)?(\([0-9]{1,4}\))?[-\s\.0-9]+$/,
21+
tel: /^(\+[0-9]{1,3}[-\s\u2011]?)?(\([0-9]{1,4}\)[-\s\u2011]?)?([0-9]+[-\s\u2011]?)*[0-9]+$/,
2122
hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i,
2223
};
2324

tests/tel.spec.ts

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,22 @@ describe('tel', () => {
6565
);
6666
});
6767

68+
it('works for us phone number with dashes', done => {
69+
new Schema({
70+
v: {
71+
type: 'tel',
72+
},
73+
}).validate(
74+
{
75+
v: '415-555-0132',
76+
},
77+
errors => {
78+
expect(errors).toBe(null);
79+
done();
80+
},
81+
);
82+
});
83+
6884
it('works for us phone number with brackets, dashes, and spaces', done => {
6985
new Schema({
7086
v: {
@@ -81,6 +97,54 @@ describe('tel', () => {
8197
);
8298
});
8399

100+
it('works for us phone number with nonbreaking hyphen', done => {
101+
new Schema({
102+
v: {
103+
type: 'tel',
104+
},
105+
}).validate(
106+
{
107+
v: '415‑555‑0132',
108+
},
109+
errors => {
110+
expect(errors).toBe(null);
111+
done();
112+
},
113+
);
114+
});
115+
116+
it('forbid multiple spaces in a row', done => {
117+
new Schema({
118+
v: {
119+
type: 'tel',
120+
},
121+
}).validate(
122+
{
123+
v: '123 456',
124+
},
125+
errors => {
126+
expect(errors[0].message).toBe('v is not a valid tel');
127+
done();
128+
},
129+
);
130+
});
131+
132+
it('forbid multiple dashes in a row', done => {
133+
new Schema({
134+
v: {
135+
type: 'tel',
136+
},
137+
}).validate(
138+
{
139+
v: '123---456',
140+
},
141+
errors => {
142+
expect(errors[0].message).toBe('v is not a valid tel');
143+
done();
144+
},
145+
);
146+
});
147+
84148
it('works for required empty string', done => {
85149
new Schema({
86150
v: {
@@ -98,5 +162,4 @@ describe('tel', () => {
98162
},
99163
);
100164
});
101-
102165
});

0 commit comments

Comments
 (0)