Home > front end >  How can I prevent form submission if value is too short?
How can I prevent form submission if value is too short?

Time:05-11

I want to prevent any form submission, if the input field is not at least 3 chars long. My button is disabled if length <= 3 but I cant prevent the submission on "Enter".

 <form name="form" action="..." method="POST" id="form">
        <div >
            <label for="name">Name</label>
            <input type="text"  id="name" name="name" required>
        </div>
        <input type="button" id="btnSubmit" value="Add" disabled>
    </form>
</div>
<script>
    const form = document.querySelector('#form');
    const inputName = document.querySelector('#name');
    const btnSubmit = document.querySelector('#btnSubmit');

    inputName.addEventListener('input', function(event) {
        btnSubmit.disabled = inputName.value.length < 3;
    });

    inputName.addEventListener('keypress', function (event){
        if (event.keyCode === 13) {
            event.preventDefault();
            if (inputName.value.length >= 3) form.submit();
        }
    });

    form.addEventListener('keypress', function (event){
        event.preventDefault();
    });

CodePudding user response:

Set a minlength value for your input field

<input type="text"  id="name" name="name"  minlength="3" required>

The minlength attribute defines the minimum number of characters (as UTF-16 code units) the user can enter into an or . This must be an integer value 0 or higher. The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length.

Source: HTML attribute: minlength

CodePudding user response:

Modify last part of your script as below:

form.addEventListener('submit', (event) => {
    event.preventDefault();
    // your actions
});

CodePudding user response:

Set a minlength value for your input field

<!DOCTYPE html>
<html>
<body>

<h1>The input minlength attribute</h1>

<form action="/action_page.php">
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" minlength="8"><br><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>

image of running code

  • Related