Open In App

How to validate Visa Card number using Regular Expression

Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

  1. It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.
  2. It should start with 4.
  3. If the cards have 13 digits the next twelve digits should be any number between 0-9.
  4. If the cards have 16 digits the next fifteen digits should be any number between 0-9.
  5. It should not contain any alphabet or special characters.

Examples: 
 

Input: str = “4155279860457”; 
Output: true 
Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid Visa Card number. 
Input: str = “4155279”; 
Output: false. 
Explanation: The given string has 7 digits. Therefore it is not a valid Visa Card number. 
Input: str = “6155279860457”; 
Output: false. 
Explanation: The given string doesn’t starts with 4. Therefore it is not a valid Visa Card number. 

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

  1. Get the String.
  2. Create a regular expression to check valid Visa Card number as mentioned below: 
     
regex = "^4[0-9]{12}(?:[0-9]{3})?$";
  1. Where: 
    • ^ represents the starting of the string.
    • 4 represents the string that should start with 4.
    • [0-9]{12} represents the next twelve digits should be any between 0-9.
    • ( represents the start of the group.
    • ? represents the 0 or 1 time.
    • [0-9]{3} represents the next three digits should be any between 0-9.
    • ) represents the ending of the group.
    • ? represents the 0 or 1 time.
    • $ represents the ending of the string.
  2. Match the given string with the Regular Expression. 
    In Java, this can be done by using Pattern.matcher().
    In C++, this can be done by using regex_match().
  3. 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
// Visa Card number
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate Visa Card number
bool isValidVisaCardNo(string str)
{
 
  // Regex to check valid Visa Card number
  const regex pattern("^4[0-9]{12}(?:[0-9]{3})?$");
 
  // If the Visa Card number
  // is empty return false
  if (str.empty())
  {
     return false;
  }
 
  // Return true if the Visa Card number
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
   
  // Test Case 1:
  string str1 = "4155279860457";
  cout << isValidVisaCardNo(str1) << endl;
 
  // Test Case 2:
  string str2 = "4155279860457201";
  cout << isValidVisaCardNo(str2) << endl;
 
  // Test Case 3:
  string str3 = "4155279";
  cout << isValidVisaCardNo(str3) << endl;
 
  // Test Case 4:
  string str4 = "6155279860457";
  cout << isValidVisaCardNo(str4) << endl;
 
  // Test Case 5:
  string str5 = "415a27##60457";
  cout << isValidVisaCardNo(str5) << endl;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra


Java




// Java program to validate
// Visa Card number
// using regular expression
import java.util.regex.*;
class GFG {
 
    // Function to validate
    // Visa Card number.
    // using regular expression.
    public static boolean
    isValidVisaCardNo(String str)
    {
        // Regex to check valid.
        // Visa Card number
        String regex = "^4[0-9]{12}(?:[0-9]{3})?$";
 
        // 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 = "4155279860457";
        System.out.println(
            isValidVisaCardNo(str1));
 
        // Test Case 2:
        String str2 = "4155279860457201";
        System.out.println(
            isValidVisaCardNo(str2));
 
        // Test Case 3:
        String str3 = "4155279";
        System.out.println(
            isValidVisaCardNo(str3));
 
        // Test Case 4:
        String str4 = "6155279860457";
        System.out.println(
            isValidVisaCardNo(str4));
 
        // Test Case 5:
        String str5 = "415a27##60457";
        System.out.println(
            isValidVisaCardNo(str5));
    }
}


Python3




# Python3 program to validate Visa
# Card number using regular expression
import re
 
# Function to validate Visa Card
# number using regular expression.
def isValidVisaCardNo(string):
     
    # Regex to check valid Visa
    # Card number
    regex = "^4[0-9]{12}(?:[0-9]{3})?$";
 
    # Compile the ReGex
    p = re.compile(regex);
     
    # If the string is empty
    # return false
    if (string == ''):
        return False;
         
    # Pattern class contains matcher()
    # method to find matching between
    # given string and regular expression.
    m = re.match(p, string);
     
    # Return True if the string
    # matched the ReGex else False
    if m is None:
        return False
    else:
        return True
 
# Driver code
if __name__ == "__main__":
     
    # Test Case 1
    str1 = "4155279860457";
    print(isValidVisaCardNo(str1));
     
    # Test Case 2
    str2 = "4155279860457201";
    print(isValidVisaCardNo(str2));
     
    # Test Case 3
    str3 = "4155279";
    print(isValidVisaCardNo(str3));
     
    # Test Case 4
    str4 = "6155279860457";
    print(isValidVisaCardNo(str4));
     
    # Test Case 5
    str5 = "415a27##60457";
    print(isValidVisaCardNo(str5));
     
# This code is contributed by AnkitRai01


C#




// C# program to validate
// Visa Card number
// using regular expression
using System;
using System.Text.RegularExpressions;
 
class GFG {
 
  // Function to validate
  // Visa Card number.
  // using regular expression.
  public static bool
    isValidVisaCardNo(string str)
  {
    // Regex to check valid.
    // Visa Card number
    string regex = "^4[0-9]{12}(?:[0-9]{3})?$";
 
    // Compile the ReGex
    Regex p = new Regex(regex);
 
    // If the string is empty
    // return false
    if (str == null) {
      return false;
    }
 
    // Find match between given string
    // and regular expression
    // using Pattern.matcher()
 
    Match m = p.Match(str);
 
    // Return if the string
    // matched the ReGex
    return m.Success;
  }
 
  // Driver code
  public static void Main()
  {
 
    // Test Case 1:
    string str1 = "4155279860457";
    Console.WriteLine(
      isValidVisaCardNo(str1));
 
    // Test Case 2:
    string str2 = "4155279860457201";
    Console.WriteLine(
      isValidVisaCardNo(str2));
 
    // Test Case 3:
    string str3 = "4155279";
    Console.WriteLine(
      isValidVisaCardNo(str3));
 
    // Test Case 4:
    string str4 = "6155279860457";
    Console.WriteLine(
      isValidVisaCardNo(str4));
 
    // Test Case 5:
    string str5 = "415a27##60457";
    Console.WriteLine(
      isValidVisaCardNo(str5));
  }
}
 
// This code is contributed by Pushpesh Raj.


Javascript




// Javascript program to validate
// Visa Card  Number  using Regular Expression
 
// Function to validate the
// Visa Card  Number 
function isValid_VisaCard_Number(VisaCard_Number) {
    // Regex to check valid
    // VisaCard_Number 
    let regex = new RegExp(/^4[0-9]{12}(?:[0-9]{3})?$/);
 
    // if VisaCard_Number
    // is empty return false
    if (VisaCard_Number == null) {
        return "false";
    }
 
    // Return true if the VisaCard_Number
    // matched the ReGex
    if (regex.test(VisaCard_Number) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "4155279860457";
console.log(isValid_VisaCard_Number(str1));
 
// Test Case 2:
let str2 = "4155279860457201";
console.log(isValid_VisaCard_Number(str2));
 
// Test Case 3:
let str3 = "4155279";
console.log(isValid_VisaCard_Number(str3));
 
// Test Case 4:
let str4 = "6155279860457";
console.log(isValid_VisaCard_Number(str4));
 
// Test Case 5:
let str5 = "415a27##60457";
console.log(isValid_VisaCard_Number(str5));
 
// Test Case 6:
let str6 = "RAH12071998";
console.log(isValid_VisaCard_Number(str6));
 
// This code is contributed by Rahul Chauhan


Output: 

true
true
false
false
false

 

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



Last Updated : 20 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads