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
- Retrieves UPI ID Value: It uses
document.getElementById
with <%=txtupiid.ClientID%>
to safely access the ASP.NET TextBox control value on the client side.
- 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.
- 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}$
^[a-zA-Z0-9._-]{2,256}
: The username part before @
can include letters, digits, dots (.), underscores (_), and hyphens (-), and must be between 2 to 256 characters.
@[a-zA-Z]{2,64}$
: The bank handle after @
must be 2 to 64 letters only.
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?
- Enhances user experience by catching errors early.
- Prevents invalid UPI submissions that could result in transaction failures.
- Saves server processing by handling checks on the client side.
Recommendations
- You can extend validation to also check whether the bank handle (e.g.,
okaxis
) exists in a pre-approved list.
- Log invalid attempts or guide users with tooltips on correct formats.
- Consider using additional security and accessibility features for production applications.