Open In App

How to validate CVV number using Regular Expression

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression
The valid CVV (Card Verification Value) number must satisfy the following conditions: 

  1. It should have 3 or 4 digits.
  2. It should have a digit between 0-9.
  3. It should not have any alphabet or special characters.

Examples: 

Input: str = “561” 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions. Therefore, it is a valid CVV (Card Verification Value) number.

Input: str = “50614” 
Output: false 
Explanation: 
The given string has five-digit. Therefore, it is not a valid CVV (Card Verification Value) number.

Input: str = “5a#1” 
Output: false 
Explanation: The given string has alphabets and special characters. Therefore, it is not a valid CVV (Card Verification Value) number. 

Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. 

  • Get the String.
  • Create a regular expression to check the valid CVV (Card Verification Value) number as mentioned below:
regex = "^[0-9]{3, 4}$";
  • Where: 
    • ^ represents the starting of the string.
    • [0-9] represents the digit between 0-9.
    • {3, 4} represents the string that has 3 or 4 digits.
    • $ represents the ending of the string.
  • Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher().
  • Return true if the string matches with the given regular expression, else return false.

Below is the implementation of the above approach:

C++




// C++ program to validate the
// CVV (Card Verification Value) number
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the CVV
// (Card Verification Value) number
bool isValidCVVNumber(string str)
{
 
    // Regex to check valid CVV
    // (Card Verification Value) number
    const regex pattern("^[0-9]{3,4}$");
 
    // If the CVV (Card Verification Value)
    //  number is empty return false
    if (str.empty())
    {
        return false;
    }
 
    // Return true if the CVV
    // (Card Verification Value) number
    // matched the ReGex
    if (regex_match(str, pattern))
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "561";
    cout << isValidCVVNumber(str1) << endl;
 
    // Test Case 2:
    string str2 = "5061";
    cout << isValidCVVNumber(str2) << endl;
 
    // Test Case 3:
    string str3 = "50614";
    cout << isValidCVVNumber(str3) << endl;
 
    // Test Case 4:
    string str4 = "5a#1";
    cout << isValidCVVNumber(str4) << endl;
 
    return 0;
}
 
// This code is contributed by yuvraj_chandra


Java




// Java program to validate
// CVV (Card Verification Value)
// number using regex.
import java.util.regex.*;
class GFG {
 
    // Function to validate
    // CVV (Card Verification Value) number.
    // using regular expression.
    public static boolean isValidCVVNumber(String str)
    {
        // Regex to check valid CVV number.
        String regex = "^[0-9]{3,4}$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (str == null)
        {
            return false;
        }
 
        // Find match between given string
        // and regular expression
        // using Pattern.matcher()
 
        Matcher m = p.matcher(str);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "561";
        System.out.println(isValidCVVNumber(str1));
 
        // Test Case 2:
        String str2 = "5061";
        System.out.println(isValidCVVNumber(str2));
 
        // Test Case 3:
        String str3 = "50614";
        System.out.println(isValidCVVNumber(str3));
 
        // Test Case 4:
        String str4 = "5a#1";
        System.out.println(isValidCVVNumber(str4));
    }
}


Python3




# Python3 program to validate
# CVV (Card Verification Value)
# number using regex.
import re
 
# Function to validate
# CVV (Card Verification Value) number.
# using regular expression.
 
 
def isValidCVVNumber(str):
 
    # Regex to check valid
    # CVV number.
    regex = "^[0-9]{3,4}$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if(str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
 
# Test Case 1:
str1 = "561"
print(isValidCVVNumber(str1))
 
# Test Case 2:
str2 = "5061"
print(isValidCVVNumber(str2))
 
# Test Case 3:
str3 = "50614"
print(isValidCVVNumber(str3))
 
# Test Case 4:
str4 = "5a#1"
print(isValidCVVNumber(str4))
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program to validate the
// CVV (Card Verification Value) number
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
 
// Main Method
static void Main(string[] args)
{
 
    // Input strings to Match
    // CVV (Card Verification Value) number
    string[] str={"561","5061","50614","5a#1"};
    foreach(string s in str) {
    Console.WriteLine( isValidCVVNumber(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
// method containing the regex
public static bool isValidCVVNumber(string str)
{
    string strRegex = @"^[0-9]{3,4}$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
    return (true);
    else
    return (false);
}
}
 
// This code is contributed by Rahul Chauhan


Javascript




// Javascript program to validate
// CVV Number  using Regular Expression
 
// Function to validate the
// CVV_Number 
function isValid_CVV_Number(CVV_Number) {
    // Regex to check valid
    // CVV_Number 
    let regex = new RegExp(/^[0-9]{3,4}$/);
 
    // if CVV_Number
    // is empty return false
    if (CVV_Number == null) {
        return "false";
    }
 
    // Return true if the CVV_Number
    // matched the ReGex
    if (regex.test(CVV_Number) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "561";
console.log(isValid_CVV_Number(str1));
 
// Test Case 2:
let str2 = "5061";
console.log(isValid_CVV_Number(str2));
 
// Test Case 3:
let str3 = "50614";
console.log(isValid_CVV_Number(str3));
 
// Test Case 4:
let str4 = "5a#1";
console.log(isValid_CVV_Number(str4));
 
// Test Case 5:
let str5 = "12071998";
console.log(isValid_CVV_Number(str5));
 
// Test Case 6:
let str6 = "RAH12071998";
console.log(isValid_CVV_Number(str6));
 
// This code is contributed by Rahul Chauhan


Output

true
true
false
false

Time Complexity: O(N) for each testcase, where N is the length of the given string. 
Auxiliary Space: O(1)  



Similar Reads

How to validate Indian driving license number using Regular Expression
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f
7 min read
How to validate SSN (Social Security Number) using Regular Expression
Given string str, the task is to check whether the given string is valid SSN (Social Security Number) or not by using Regular Expression. The valid SSN (Social Security Number) must satisfy the following conditions: It should have 9 digits.It should be divided into 3 parts by hyphen (-).The first part should have 3 digits and should not be 000, 666
6 min read
Validate Corporate Identification Number (CIN) using Regular Expression
Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are occupied by alphabet letters(A-Z-a-z).Next four pl
6 min read
How to validate PAN Card number using Regular Expression
Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters should be any upper case alphabets.The next four-cha
6 min read
How to validate GST (Goods and Services Tax) number using Regular Expression
Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number
6 min read
How to validate MasterCard number using Regular Expression
Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. The valid Master Card number must satisfy the following conditions. It should be 16 digits long.It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.In
7 min read
How to validate Visa Card number using Regular Expression
Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start with 4.If the cards have 13 digits the next twelv
6 min read
How to validate Indian Passport number using Regular Expression
Given a string str of alphanumeric characters, the task is to check whether the given string is a valid passport number or not by using Regular Expression. A valid passport number in India must satisfy the following conditions: It should be eight characters long.The first character should be an uppercase alphabet.The next two characters should be a
6 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
How to validate identifier using Regular Expression in Java
Given a string str, the task is to check whether the string is a valid identifier or not using the Regular Expression. The valid rules for defining Java identifiers are: It must start with either lower case alphabet[a-z] or upper case alphabet[A-Z] or underscore(_) or a dollar sign($).It should be a single word, the white spaces are not allowed.It
2 min read