Validating UPI ID in JavaScript: Ensuring Proper Format and Input

In web applications involving payment or identity verification, validating user input such as a UPI (Unified Payments Interface) ID is essential. The following JavaScript snippet demonstrates how to validate a UPI ID in an ASP.NET environment using client-side validation:

Code Explanation

var UPIID = document.getElementById("<%=txtupiid.ClientID%>").value;

// Step 1: Check if UPI ID field is empty
if (UPIID.trim() === "") {
    alertify.alert("Please enter the VPA");
    document.getElementById("<%=txtupiid.ClientID%>").focus();
    return false;
}

// Step 2: Validate UPI ID format using Regular Expression
var upiRegex = /^[a-zA-Z0-9._-]{2,256}@[a-zA-Z]{2,64}$/;
if (!upiRegex.test(UPIID.trim())) {
    alertify.alert("Invalid UPI ID format. It should be like name@bank");
    document.getElementById("<%=txtupiid.ClientID%>").focus();
    return false;
}

What This Code Does

  1. Retrieves UPI ID Value: It uses document.getElementById with <%=txtupiid.ClientID%> to safely access the ASP.NET TextBox control value on the client side.
  2. Checks for Empty Input: If the field is left empty, it triggers an alert:
    "Please enter the VPA", and focuses back on the input field.
  3. Validates the UPI Format: Uses a regular expression (upiRegex) to ensure the UPI ID is in a valid format, i.e., contains a username and bank handle separated by @.

Regular Expression Breakdown

^[a-zA-Z0-9._-]{2,256}@[a-zA-Z]{2,64}$

Example of Valid UPI IDs

Input Validity
john.doe@okaxis Valid
user123@oksbi Valid
name_2024@okicici Valid
@oksbi Invalid
john@ Invalid

Why Use This?

Recommendations