seeb4coding_post_placeholder

How to Add Regex Patterns for Input Validation

1. Allow Only Numbers

Regex: /[^0-9]/g

Description: Removes all non-numeric characters, allowing only numbers.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9]/g, '');
});

Use Case: Validating fields like phone numbers or numeric IDs.


2. Allow Only Numbers and One Decimal Point

Regex: /[^0-9.]/g

Description: Removes all characters except numbers and a single decimal point. Handles extra decimal points with additional logic.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9.]/g, '');
    if (input.value.split('.').length > 2) {
        input.value = input.value.replace(/\.(?=.*\.)/, '');
    }
});

Use Case: Useful for fields like price or weight input.


3. Allow Only Numbers and One Space

Regex: /[^0-9 ]/g

Description: Removes all characters except numbers and a single space. Extra spaces are removed with additional logic.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9 ]/g, '');
    if (input.value.split(' ').length > 2) {
        input.value = input.value.replace(/ (?!.* )/, '');
    }
});

Use Case: Validating fields like phone numbers with extensions.


4. Allow Only Letters and One Space

Regex: /[^a-zA-Z ]/g

Description: Restricts the input to letters and a single space.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z ]/g, '');
    if (input.value.split(' ').length > 2) {
        input.value = input.value.replace(/ (?!.* )/, '');
    }
});

Use Case: Validating names or other single-space strings.


5. Allow Only Letters

Regex: /[^a-zA-Z]/g

Description: Removes all characters that are not letters.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z]/g, '');
});

Use Case: Useful for name or text-only fields.


6. Allow Only Letters and Numbers (No Special Characters or Spaces)

Regex: /[^a-zA-Z0-9]/g

Description: Removes spaces and special characters, allowing only alphanumeric characters.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z0-9]/g, '');
});

Use Case: Suitable for fields like usernames or alphanumeric codes.


7. Allow Letters, Numbers, and Limited Special Characters

Regex: /[^a-zA-Z0-9@#%&]/g

Description: Restricts input to alphanumeric characters and a few special characters (@, #, %, &).

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z0-9@#%&]/g, '');
});

Use Case: Used for complex fields like passwords or secure IDs.


8. Allow Only Letters and Spaces (No Numbers or Special Characters)

Regex: /[^a-zA-Z ]/g

Description: Allows letters and spaces only.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z ]/g, '');
});

Use Case: Useful for fields like full names or titles.


9. Allow Alphanumeric Characters and Spaces (No Special Characters)

Regex: /[^a-zA-Z0-9 ]/g

Description: Allows letters, numbers, and spaces, but no special characters.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z0-9 ]/g, '');
});

Use Case: Validating product names or descriptive fields.


10. Allow Email Format (Basic)

Regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/

Description: Validates an email format. Note: Use this regex in a test() method to check email validity.

Example Code Snippet:

input.addEventListener('blur', () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(input.value)) {
        alert('Invalid email format');
    }
});

Use Case: Basic email validation for user input.

11. Allow Only Lowercase Letters

Regex: /[^a-z]/g

Description: Removes all characters that are not lowercase letters.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-z]/g, '');
});

Use Case: Useful for fields requiring lowercase-only text, such as unique lowercase IDs or passwords.


12. Allow Only Uppercase Letters

Regex: /[^A-Z]/g

Description: Removes all characters that are not uppercase letters.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^A-Z]/g, '');
});

Use Case: Validating fields that need uppercase-only input, such as codes or acronyms.


13. Allow Only Numbers with Optional Leading Zeros

Regex: /[^0-9]/g

Description: Restricts input to numbers, including those with leading zeros (e.g., “00123”).

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9]/g, '');
});

Use Case: Useful for IDs or other numeric fields where leading zeros must be preserved.


14. Allow Only Hexadecimal Characters

Regex: /[^a-fA-F0-9]/g

Description: Removes all characters that are not hexadecimal (0-9, a-f, A-F).

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-fA-F0-9]/g, '');
});

Use Case: Validating hexadecimal color codes or hash values.


15. Allow Only Numbers with Specific Length (e.g., Exactly 5 Digits)

Regex: /^\d{5}$/

Description: Matches input that is exactly 5 digits long. Use this in a test() method for validation.

Example Code Snippet:

input.addEventListener('blur', () => {
    const regex = /^\d{5}$/;
    if (!regex.test(input.value)) {
        alert('Input must be exactly 5 digits');
    }
});

Use Case: Validating postal codes or identification numbers with a fixed length.


16. Allow Only Valid Date Format (e.g., YYYY-MM-DD)

Regex: /^\d{4}-\d{2}-\d{2}$/

Description: Validates dates in the format YYYY-MM-DD.

Example Code Snippet:

input.addEventListener('blur', () => {
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateRegex.test(input.value)) {
        alert('Invalid date format. Use YYYY-MM-DD');
    }
});

Use Case: Ensuring proper date input in forms.


17. Allow URLs (Basic)

Regex: /^(https?:\/\/)?([\w\-]+\.)+[\w]{2,}(\/\S*)?$/

Description: Validates a basic URL format. Use this regex in a test() method for URL validation.

Example Code Snippet:

input.addEventListener('blur', () => {
    const urlRegex = /^(https?:\/\/)?([\w\-]+\.)+[\w]{2,}(\/\S*)?$/;
    if (!urlRegex.test(input.value)) {
        alert('Invalid URL');
    }
});

Use Case: Checking URLs in form fields or link inputs.


18. Allow Positive and Negative Numbers (Including Decimals)

Regex: /^-?\d*\.?\d*$/

Description: Allows numbers, including negatives and decimals.

Example Code Snippet:

input.addEventListener('input', () => {
    if (!/^-?\d*\.?\d*$/.test(input.value)) {
        input.value = input.value.slice(0, -1); // Remove last character if invalid
    }
});

Use Case: Validating inputs for both positive and negative decimal numbers, like coordinates or financial data.


19. Allow Only Letters and Hyphens (e.g., Last Names)

Regex: /[^a-zA-Z-]/g

Description: Removes all characters except letters and hyphens.

Example Code Snippet:

input.addEventListener('input', () => {
    input.value = input.value.replace(/[^a-zA-Z-]/g, '');
});

Use Case: Validating last names or names that may include a hyphen (e.g., “Smith-Jones”).


20. Allow Passwords with Specific Rules (e.g., One Uppercase, One Lowercase, One Number, and One Special Character)

Regex: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}/

Description: Checks for at least one lowercase letter, one uppercase letter, one number, and one special character. The length should be at least 8 characters.

Example Code Snippet:

input.addEventListener('blur', () => {
    const passwordRegex = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}/;
    if (!passwordRegex.test(input.value)) {
        alert('Password must contain uppercase, lowercase, a number, a special character, and be at least 8 characters long');
    }
});

Use Case: Ensuring strong passwords for account security.

21. Automatically Format Numbers with Commas (e.g., 10000 becomes 10,000)

Regex: /\B(?=(\d{3})+(?!\d))/g

Description: Automatically inserts commas in the correct positions as the user types, formatting numbers like 10000 to 10,000.

Example Code Snippet:

const input = document.querySelector('#numberInput');

input.addEventListener('input', () => {
    let value = input.value.replace(/,/g, ''); // Remove existing commas
    if (!isNaN(value) && value.length > 0) {
        // Apply formatting only if the number is 5 digits or more
        if (value.length >= 5) {
            input.value = parseFloat(value).toLocaleString('en-US');
        } else {
            input.value = value; // Keep the number unformatted if less than 5 digits
        }
    }
});

Use Case: Useful for formatting large numbers, such as currency, population, or any data that benefits from comma-separated readability.

22. Format Numbers According to the Indian Numbering System (e.g., 100000 becomes 1,00,000)

Regex: /\B(?=(\d{2})+(?!\d))/g

Description: Formats numbers in the Indian numbering style, which places a comma after the first three digits and then every two digits. This is useful for displaying large numbers like amounts in rupees.

Example Code Snippet:

const input = document.querySelector('#numberInput');

input.addEventListener('input', () => {
    let value = input.value.replace(/,/g, ''); // Remove existing commas
    if (!isNaN(value) && value.length > 0) {
        input.value = formatNumberToIndianStyle(value);
    }
});

function formatNumberToIndianStyle(number) {
    let x = number.toString();
    let lastThree = x.substring(x.length - 3); // Extract the last three digits
    let otherNumbers = x.substring(0, x.length - 3); // Extract the remaining digits
    if (otherNumbers !== '') {
        lastThree = ',' + lastThree;
    }
    let formattedNumber = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
    return formattedNumber;
}

Use Case: Useful for financial applications, e-commerce platforms, or any system that needs to display numbers in the Indian numbering format, enhancing readability and comprehension for users familiar with this system.

Conclusion

Using JavaScript to format numbers based on specific regional or custom requirements can greatly enhance the user experience of your application. Here’s a summary of the techniques we’ve covered:

  • Regex Patterns for Formatting: Using regular expressions to add commas in numbers based on different styles, like the Indian or international numbering system.
  • Conditional Formatting: Applying conditions to ensure that formatting only occurs when necessary, like when numbers reach a certain length.
  • Practical Applications: These solutions are particularly helpful in financial applications, e-commerce, or any interface where large numeric values need to be easily readable.

By implementing such formatting, you provide clarity and ensure your application meets the expectations of its audience, whether they are familiar with the Western or Indian numeral system. Additionally, knowing how to tailor these patterns gives you more flexibility in data representation and makes your application more user-friendly.

Leave a Reply

Your email address will not be published. Required fields are marked *