Skip to content

Commit bcbf80c

Browse files
authored
Validate a credit card number (#1430)
* Script.js * readme.md
1 parent 7337afd commit bcbf80c

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function onSubmit() {
2+
var cardNumber = g_form.getValue('credit_card'); // Change 'credit_card' to your field name
3+
var cardPattern = /^\d{16}$/; // Simple pattern for 16-digit cards
4+
5+
if (!cardPattern.test(cardNumber) || !isValidCardNumber(cardNumber)) {
6+
g_form.showFieldMsg('credit_card', 'Please enter a valid 16-digit credit card number.', 'error');
7+
return false;
8+
}
9+
return true;
10+
}
11+
12+
function isValidCardNumber(number) {
13+
var sum = 0;
14+
var alternate = false;
15+
for (var i = number.length - 1; i >= 0; i--) {
16+
var n = parseInt(number.charAt(i), 10);
17+
if (alternate) {
18+
n *= 2;
19+
if (n > 9) n -= 9;
20+
}
21+
sum += n;
22+
alternate = !alternate;
23+
}
24+
return sum % 10 === 0;
25+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
**Description of the Credit Card Number Validation Script**
2+
Purpose
3+
The script validates a credit card number entered by the user in a ServiceNow form.
4+
It checks if the number is a valid 16-digit credit card number using a combination of a regular expression and the Luhn algorithm for basic validation.
5+
6+
**Validation Criteria**
7+
Format:
8+
The credit card number must consist of exactly 16 digits.
9+
**Luhn Algorithm:**
10+
The script implements the Luhn algorithm to determine if the credit card number is potentially valid.
11+
This algorithm helps catch common errors in credit card numbers, such as transposed digits.

0 commit comments

Comments
 (0)