/
validators.go
522 lines (469 loc) · 15.2 KB
/
validators.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// Licensed to The Moov Authors under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. The Moov Authors licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package ach
import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"unicode/utf8"
)
var (
upperAlphanumericRegex = regexp.MustCompile(fmt.Sprintf(
`[^ A-Z0-9!"#$%%&'()*+,-.\\/:;<>=?@\[\]^_{}|~%s]+`, "`"))
alphanumericRegex = regexp.MustCompile(fmt.Sprintf(
`[^ \w!"#$%%&'()*+,-.\\/:;<>=?@\[\]^_{}|~%s]+`, "`"))
)
// validator is common validation and formatting of golang types to ach type strings
type validator struct{}
// isCardTransactionType ensures card transaction type of a batchPOS is valid
func (v *validator) isCardTransactionType(code string) error {
switch code {
case
// Purchase of goods or services
"01",
// Cash
"02",
// Return Reversal
"03",
// Purchase Reversal
"11",
// Cash Reversal
"12",
// Return
"13",
// Adjustment
"21",
// Miscellaneous Transaction
"99":
return nil
}
return ErrCardTransactionType
}
// isYear validates a 2 digit year 00-99
func (v *validator) isYear(s string) error {
if s < "00" || s > "99" {
return ErrValidYear
}
return nil
}
// isCreditCardYear validates a 2 digit year for credit cards, but
// only accepts a range of years. 2018 to 2050
func (v *validator) isCreditCardYear(s string) error {
if s < "18" || s > "50" {
return ErrValidYear
}
return nil
}
// isMonth validates a 2 digit month 01-12
func (v *validator) isMonth(s string) error {
switch s {
case
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12":
return nil
}
return ErrValidMonth
}
// isDay validates a 2 digit day based on a 2 digit month
// month 01-12 day 01-31 based on month
func (v *validator) isDay(m string, d string) error {
// ToDo: Future Consideration Leap Year - not sure if cards actually have 0229
switch m {
// February
case "02":
switch d {
case
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12",
"13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29":
return nil
}
// April, June, September, November
case "04", "06", "09", "11":
switch d {
case
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12",
"13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30":
return nil
}
// January, March, May, July, August, October, December
case "01", "03", "05", "07", "08", "10", "12":
switch d {
case
"01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12",
"13", "14", "15", "16", "17", "18",
"19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31":
return nil
}
}
return ErrValidDay
}
// validateSimpleDate will return the incoming string only if it matches a valid YYMMDD
// date format. (Y=Year, M=Month, D=Day)
func (v *validator) validateSimpleDate(s string) string {
if length := utf8.RuneCountInString(s); length != 6 {
return ""
}
yy, mm, dd := s[:2], s[2:4], s[4:6]
if err := v.isYear(yy); err != nil {
return ""
}
if err := v.isMonth(mm); err != nil {
return ""
}
if err := v.isDay(mm, dd); err != nil {
return ""
}
return fmt.Sprintf("%s%s%s", yy, mm, dd)
}
var (
// hhmmRegex defines a regex for all valid 24-hour clock timestamps.
// Format: HHmm (H=hour, m=minute) - (first H can only be 0, 1, or 2)
hhmmRegex = regexp.MustCompile(`^([0-2]{1}[\d]{1}[0-5]{1}\d{1})$`)
)
// validateSimpleTime will return the incoming string only if it is a valid 24-hour clock time.
func (v *validator) validateSimpleTime(s string) string {
if hhmmRegex.MatchString(s) {
return s // successfully matched and validated
}
return ""
}
// isForeignExchangeIndicator ensures foreign exchange indicators of an
// IATBatchHeader is valid
func (v *validator) isForeignExchangeIndicator(code string) error {
switch code {
case
"FV", "VF", "FF":
return nil
}
return ErrForeignExchangeIndicator
}
// isForeignExchangeReferenceIndicator ensures foreign exchange reference
// indicator of am IATBatchHeader is valid
func (v *validator) isForeignExchangeReferenceIndicator(code int) error {
switch code {
case
1, 2, 3:
return nil
}
return ErrForeignExchangeReferenceIndicator
}
// isIDNumberQualifier ensures ODFI Identification Number Qualifier is valid
// For Inbound IATs: The 2-digit code that identifies the numbering scheme used in the
// Foreign DFI Identification Number field:
// 01 = National Clearing System
// 02 = BIC Code
// 03 = IBAN Code
// used for both ODFIIDNumberQualifier and RDFIIDNumberQualifier
func (v *validator) isIDNumberQualifier(s string) error {
switch s {
case
"01", "02", "03":
return nil
}
return ErrIDNumberQualifier
}
// isOriginatorStatusCode ensures status code of a batch is valid
func (v *validator) isOriginatorStatusCode(code int) error {
switch code {
case
// ADV file - prepared by an ACH Operator
0,
// Originator is a financial institution
1,
// Originator is a Government Agency or other agency not subject to ACH Rules
2:
return nil
}
return ErrOrigStatusCode
}
// isSECCode returns true if a SEC Code of a Batch is found
func (v *validator) isSECCode(code string) error {
switch code {
case
ACK, ADV, ARC, ATX, BOC, CCD, CIE, COR, CTX, DNE, ENR,
IAT, MTE, POS, PPD, POP, RCK, SHR, TEL, TRC, TRX, WEB, XCK:
return nil
}
return ErrSECCode
}
// iServiceClass returns true if a valid service class code of a batch is found
func (v *validator) isServiceClass(code int) error {
switch code {
case
// Mixed Debits and Credits
MixedDebitsAndCredits,
// Credits Only
CreditsOnly,
// Debits Only
DebitsOnly,
// Automated Accounting Advices
AutomatedAccountingAdvices:
return nil
}
return ErrServiceClass
}
// isTypeCode returns true if a valid type code of an Addendum is found
//
// The Addenda Type Code defines the specific interpretation and format for the addenda information contained in the Entry.
func (v *validator) isTypeCode(code string) error {
switch code {
case
// For POS, SHR or MTE Entries
"02",
// Addenda Record
"08",
// Notification of Change and Refused Notification of Change Entry
"98",
// Return, Dishonored Return and Contested Dishonored Return Entries
"99",
// IAT forward Entries and IAT Returns
"10", "11", "12", "13", "14", "15", "16", "17", "18",
// ACK, ATX, CCD, CIE, CTX, DNE, ENR, PPD, TRX and WEB Entries
"05":
return nil
}
return ErrAddendaTypeCode
}
// isTransactionCode ensures TransactionCode of an Entry is valid
//
// The Tran Code is a two-digit code in positions 2 - 3 of the Entry Detail Record (6 Record) within an ACH File.
// The first digit of the Tran Code indicates the account type to which the entry will post, where the number:
// "2" designates a Checking Account.
// "3" designates a Savings Account.
// "4" designates a General Ledger Account.
// "5" designates Loan Account.
//The second digit of the Tran Code identifies the entry as:
// an original forward entry, where the number:
// "2" designates a credit. or
// "7" designates a debit.
// a return or NOC, where the number:
// "1" designates the return/NOC of a credit, or
// "6" designates a return/NOC of a debit.
// a pre-note or non-monetary informational transaction, where the number:
// "3" designates a credit, or
// "8" designates a debit.
func (v *validator) isTransactionCode(code int) error {
return StandardTransactionCode(code)
}
// StandardTransactionCode checks the provided TransactionCode to verify it is a valid NACHA value.
func StandardTransactionCode(code int) error {
switch code {
// TransactionCode if the receivers account is:
case
// Demand Credit Records (for checking, NOW, and share draft accounts)
// Automated Return or Notification of Change for original transaction code '22', '23, '24'
CheckingReturnNOCCredit,
// Credit (deposit) to checking account '22'
CheckingCredit,
// Prenote for credit to checking account '23'
CheckingPrenoteCredit,
// Zero dollar with remittance data
CheckingZeroDollarRemittanceCredit,
// Demand Debit Records (for checking, NOW, and share draft accounts)
// Automated Return or Notification of Change for original transaction code 27, 28, or 29
CheckingReturnNOCDebit,
// Debit (withdrawal) to checking account '27'
CheckingDebit,
// Prenote for debit to checking account '28'
CheckingPrenoteDebit,
// Zero dollar with remittance data (for CCD, CTX, and IAT Entries only)
CheckingZeroDollarRemittanceDebit,
// Savings Account Credit Records
// Return or Notification of Change for original transaction code 32, 33, or 34
SavingsReturnNOCCredit,
// Credit to savings account '32'
SavingsCredit,
// Prenote for credit to savings account '33'
SavingsPrenoteCredit,
// Zero dollar with remittance data (for CCD, CTX, and IAT Entries only); Acknowledgment Entries (ACK and ATX Entries only)
SavingsZeroDollarRemittanceCredit,
// Savings Account Debit Records
// Automated Return or Notification of Change for original transaction code '37', '38', '39
SavingsReturnNOCDebit,
// Debit to savings account '37'
SavingsDebit,
// Prenote for debit to savings account '38'
SavingsPrenoteDebit,
// Zero dollar with remittance data
SavingsZeroDollarRemittanceDebit,
// Financial Institution General Ledger Credit Records
//Return or Notification of Change for original transaction code 42, 43, or 44
GLReturnNOCCredit,
// General Ledger Credit
GLCredit,
// Prenotification of General Ledger Credit (non-dollar)
GLPrenoteCredit,
// Zero dollar with remittance data
GLZeroDollarRemittanceCredit,
// Financial Institution General Ledger Debit Records
// Return or Notification of Change for original transaction code 47, 48, or 49
GLReturnNOCDebit,
//General Ledger Debit
GLDebit,
// Prenotification of General Ledger Debit (non-dollar)
GLPrenoteDebit,
// Zero dollar with remittance data
GLZeroDollarRemittanceDebit,
// Loan Account Credit Records
// Return or Notification of Change for original transaction code 52, 53, or 54
LoanReturnNOCCredit,
// Loan Account Credit
LoanCredit,
// Prenotification of Loan Account Credit (non-dollar)
LoanPrenoteCredit,
// Zero dollar with remittance data
LoanZeroDollarRemittanceCredit,
// Loan Account Debit Records (for Reversals Only)
// Loan Account Debit (Reversals Only)
LoanDebit,
// Return or Notification of Change for original transaction code 55
LoanReturnNOCDebit,
// Accounting Records (for use in ADV Files only)
// These transaction codes represent accounting Entries.
// Credit for ACH debits originated
CreditForDebitsOriginated,
//Debit for ACH credits originated
DebitForCreditsOriginated,
// Credit for ACH credits received
CreditForCreditsReceived,
// Debit for ACH debits received
DebitForDebitsReceived,
// Credit for ACH credits in Rejected batches
CreditForCreditsRejected,
// Debit for ACH debits in Rejected batches
DebitForDebitsRejectedBatches,
// Summary credit for respondent ACH activity
CreditSummary,
// Summary debit for respondent ACH activity
DebitSummary:
return nil
}
return ErrTransactionCode
}
// isTransactionTypeCode verifies Addenda10 TransactionTypeCode is a valid value
// ANN = Annuity, BUS = Business/Commercial, DEP = Deposit, LOA = Loan, MIS = Miscellaneous, MOR = Mortgage
// PEN = Pension, RLS = Rent/Lease, REM = Remittance2, SAL = Salary/Payroll, TAX = Tax, TEL = Telephone-Initiated Transaction
// WEB = Internet-Initiated Transaction, ARC = Accounts Receivable Entry, BOC = Back Office Conversion Entry,
// POP = Point of Purchase Entry, RCK = Re-presented Check Entry
func (v *validator) isTransactionTypeCode(s string) error {
switch s {
case "ANN", "BUS", "DEP", "LOA", "MIS", "MOR",
"PEN", "RLS", "REM", "SAL", "TAX", TEL, WEB,
ARC, BOC, POP, RCK:
return nil
}
return ErrTransactionTypeCode
}
// isUpperAlphanumeric checks if string only contains ASCII alphanumeric upper case characters
func (v *validator) isUpperAlphanumeric(s string) error {
if upperAlphanumericRegex.MatchString(s) {
return ErrUpperAlpha
}
return nil
}
// isAlphanumeric checks if a string only contains ASCII alphanumeric characters
func (v *validator) isAlphanumeric(s string) error {
if alphanumericRegex.MatchString(s) {
// ^[ A-Za-z0-9_@./#&+-]*$/
return ErrNonAlphanumeric
}
return nil
}
// CalculateCheckDigit returns a check digit for a routing number
// Multiply each digit in the Routing number by a weighting factor. The weighting factors for each digit are:
// Position: 1 2 3 4 5 6 7 8
// Weights : 3 7 1 3 7 1 3 7
// Add the results of the eight multiplications
// Subtract the sum from the next highest multiple of 10.
// The result is the Check Digit
func (v *validator) CalculateCheckDigit(routingNumber string) int {
if n := utf8.RuneCountInString(routingNumber); n != 8 && n != 9 {
return -1
}
var routeIndex [8]string
for i := 0; i < 8; i++ {
if routingNumber[i] < '0' || routingNumber[i] > '9' {
return -1 // only digits are allowed
}
routeIndex[i] = string(routingNumber[i])
}
n, _ := strconv.Atoi(routeIndex[0])
sum := n * 3
n, _ = strconv.Atoi(routeIndex[1])
sum = sum + (n * 7)
n, _ = strconv.Atoi(routeIndex[2])
sum = sum + n // multiply by 1
n, _ = strconv.Atoi(routeIndex[3])
sum = sum + (n * 3)
n, _ = strconv.Atoi(routeIndex[4])
sum = sum + (n * 7)
n, _ = strconv.Atoi(routeIndex[5])
sum = sum + n // multiply by 1
n, _ = strconv.Atoi(routeIndex[6])
sum = sum + (n * 3)
n, _ = strconv.Atoi(routeIndex[7])
sum = sum + (n * 7)
return v.roundUp10(sum) - sum
}
// CheckRoutingNumber returns a nil error if the provided routingNumber is valid according to
// NACHA rules. See CalculateCheckDigit for details on computing the check digit.
func CheckRoutingNumber(routingNumber string) error {
if routingNumber == "" {
return errors.New("no routing number provided")
}
if n := utf8.RuneCountInString(routingNumber); n != 9 {
return fmt.Errorf("invalid routing number length of %d", n)
}
v := new(validator)
check := fmt.Sprintf("%d", v.CalculateCheckDigit(routingNumber))
last := string(routingNumber[len(routingNumber)-1])
if check != last {
return fmt.Errorf("routing number checksum mismatch: expected %s but got %s", check, last)
}
return nil
}
// roundUp10 round number up to the next ten spot.
func (v *validator) roundUp10(n int) int {
return int(math.Ceil(float64(n)/10.0)) * 10
}
func (v *validator) validateSettlementDate(s string) string {
emptyField := " "
if s == emptyField {
return s
}
if len(s) != len(emptyField) {
return emptyField
}
day, err := strconv.Atoi(s)
if err != nil {
return emptyField
}
if day < 1 || day > 366 {
return emptyField
}
return s
}