javascriptformscharacterletter

I want to prevent numbers and special characters in an input, to force a character in the first position


I have already been successful in doing these other things:

This is how I did all of the mentioned above:

function SpaceBlock() {
    var space = document.getElementById("real_name");
        if(space.selectionStart === 0 && window.event.code === "Space"){
            window.event.preventDefault(); } }

function SpaceBlock2() {
    var space = document.getElementById("display_name");
        if(space.selectionStart === 0 && window.event.code === "Space"){
            window.event.preventDefault();} }
            
var lastkey;
var ignoreChars = ' \r\n'+String.fromCharCode(0);
function ignoreSpaces(e) {
    e = e || window.event;
    var char = String.fromCharCode(e.charCode);
    if(ignoreChars.indexOf(char) >= 0 && ignoreChars.indexOf(lastkey) >= 0) {
        lastkey = char;
        return false; }
    else {
        lastkey = char;
        return true; } }

var lastkey2;
var ignoreChars2 = ' \r\n'+String.fromCharCode(0);
function ignoreSpaces2(e) {
    e = e || window.event;
    var char2 = String.fromCharCode(e.charCode);
    if(ignoreChars2.indexOf(char2) >= 0 && ignoreChars2.indexOf(lastkey2) >= 0) {
        lastkey2 = char2;
        return false; }
    else {
        lastkey2 = char2;
        return true; } }
<input type="text" name="real_name" placeholder="Real Name" id="real_name" required minlength="6" maxlength="24" tabindex="1" onkeydown="SpaceBlock()" onkeypress="return ignoreSpaces(event);" style="text-transform: capitalize;" >

<input type="text" name="display_name" placeholder="Display Name" id="display_name" required minlength="6" maxlength="24" tabindex="1" onkeydown="SpaceBlock()" onkeypress="return ignoreSpaces(event);" style="text-transform: capitalize;" >

This is the last thing I need for my form, just hoping someone will help. Thanks!


Solution

  • Here's an enhanced and more organized solution that handles below cases:

    1. Preventing the first character from being a space.
    2. Preventing consecutive spaces.
    3. Forcing each word in the input to be capitalized.
    4. Ensuring the first character is a letter, not a number or special character.

    document.addEventListener("DOMContentLoaded", function () {
        // Function to handle all keypress events
        function handleKeyPress(event) {
            const input = event.target;
            const char = String.fromCharCode(event.which);
    
            // Prevent first character from being a space
            if (input.selectionStart === 0 && event.code === "Space") {
                event.preventDefault();
                return;
            }
    
            // Prevent first character from being a non-letter
            if (input.selectionStart === 0 && !/^[a-zA-Z]$/.test(char)) {
                event.preventDefault();
                return;
            }
    
            // Prevent consecutive spaces
            const lastChar = input.value.charAt(input.selectionStart - 1);
            if (char === " " && lastChar === " ") {
                event.preventDefault();
                return;
            }
        }
    
        // Attach event listeners to input fields
        const inputs = document.querySelectorAll("input[name='real_name'], input[name='display_name']");
        inputs.forEach(input => {
            input.addEventListener("keypress", handleKeyPress);
    
            // Set text-transform to capitalize to force capitalization of each word
            input.style.textTransform = "capitalize";
        });
    });
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <input
          type="text"
          name="real_name"
          placeholder="Real Name"
          id="real_name"
          required
          minlength="6"
          maxlength="24"
          tabindex="1"
        />
    
        <input
          type="text"
          name="display_name"
          placeholder="Display Name"
          id="display_name"
          required
          minlength="6"
          maxlength="24"
          tabindex="2"
        />
        <script src="./temp.js"></script>
      </body>
    </html>