Home > Net >  How do I show alert message and disable the button if the input is not accepted on keyup?
How do I show alert message and disable the button if the input is not accepted on keyup?

Time:09-21

I have an input field that is listening to keyup event. It is checking the usernames uniqueness . I have a page full of forms that user have to fill in. One of it is to check if the username is unique.

The username has 3 restrictions.

  1. Must be unique
  2. Must be in lowercase.
  3. Only alphanumeric is accepted.

I have no issue with the restrictions but I have a problem with displaying the alert message and disabling the proceed button.

In real development I use API to check the username, but you got the idea how I wanted to solve this problem. The real problem is, even if the username is valid it is still showing the error message. It did not refresh the isUsernameUnique value. How do I solve this ?

$(document).ready(function() {
  let isUsernameUnique = false;
  $('#nextButton').prop('disabled', false);
  $('#nextButton').click(function(e) {
    e.preventDefault();

    let year = $("#year").val();
    let email = $("#email").val();
    let username = $("#username").val();


    if (isUsernameUnique == true) {
      Swal.fire({
        icon: "warning",
        text: 'Sorry this username already exists'
      });
      $('#nextButton').prop('disabled', true);
    }

    if (year != "" && email != "" && username != "") {
      $('#nextButton').prop('disabled', false);
    } else {
      Swal.fire({
        icon: "warning",
        text: 'Please fill in all the information !'
      });
    }

  });


  $('#username').keyup(function() {
let checkUsername = $(this).val($(this).val().toLowerCase()).val();


    if (checkUsername == 'cindy90' || checkUsername == 'lilycollin' || checkUsername == 'adrian98') {
      $('#usernameValid').html(`<span style="color:red;"><b> (Invalid )</b></span>`);
      isUsernameUnique = false;
    } else
      $('#usernameValid').html(`<span style="color:green;"><b> (Valid) </b></span>`);
    isUsernameUnique = true;

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="col-lg-6 mb-30 ">
  <label><b><span style="color:#e60000;">*</span> Username</i></b> <span id="usernameValid"></span></label><br>
  <div class="input-group-prepend">
    <input class="from-control" type="text" id="username" onkeypress="return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 97 && event.charCode <= 122) && (event.charCode != 32))">
  </div>
</div>
<div class="col-lg-6 mb-30 ">
  <label><b><span style="color:#e60000;">*</span> Year</i></b></span></label><br>
  <div class="input-group-prepend">
    <input class="from-control" type="text" id="year">
  </div>
</div>
<div class="col-lg-6 mb-30 ">
  <label><b><span style="color:#e60000;">*</span> Email</i></b></span></label><br>
  <div class="input-group-prepend">
    <input class="from-control" type="email" id="email">
  </div>
</div>

<button id="nextButton">Next</button>

CodePudding user response:

Several things

I suggest to make small functions that do one or two things only I also suggest to use the submit event instead of the click event to test the validity

Actually doing that will make some of the things unnecessary

const checkUser = () => {
  const checkUsername = $("#username").val().trim().toLowerCase();
  if (!checkUsername) return true
  const isUsernameUnique = !['cindy90', 'lilycollin', 'adrian98'].includes(checkUsername)
  if (isUsernameUnique)
    $('#usernameValid').html(`<span style="color:green;"><b> (Valid) </b></span>`);
  else
    $('#usernameValid').html(`<span style="color:red;"><b> (Invalid )</b></span>`);
  if (!isUsernameUnique) {
    Swal.fire({
      icon: "warning",
      text: 'Sorry this username already exists'
    });
  }

  return isUsernameUnique;
}

const checkEntries = () => {
  let year = $("#year").val().trim();
  let email = $("#email").val().trim();
  let username = $("#username").val().trim();
  return year !== "" && email !== "" && username !== "";
}

const isValid = () => checkUser() && checkEntries();

$(function() {

  $('#username').on("input", checkUser)
  $('#myForm').on("submit", function(e) {


    if (!checkEntries()) {
      Swal.fire({
        icon: "warning",
        text: 'Please fill in all the information !'
      });
    }


    if (!isValid()) e.preventDefault();
  })
  $('#myForm').on("input", function(e) {
    $('#nextButton').prop('disabled', !isValid());
  })
  $('#nextButton').prop('disabled', !isValid());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<form id="myForm">
  <div class="col-lg-6 mb-30 ">
    <label>
      <span style="color:#e60000;"><b>*</b></span> 
      <b><i>Username</i></b> <span id="usernameValid"></span></label>
    <div class="input-group-prepend">
      <input class="form-control" type="text" id="username" onkeypress="return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 97 && event.charCode <= 122) && (event.charCode != 32))" />
    </div>
  </div>
  <div class="col-lg-6 mb-30 ">
    <label><span style="color:#e60000;"><b>*</b></span><b><i>Year</i></b></label>
    <div class="input-group-prepend">
      <input class="form-control" type="text" id="year">
    </div>
  </div>
  <div class="col-lg-6 mb-30 ">
    <label><span style="color:#e60000;"><b>*</b></span><b><i>Email</i></b></label>
    <div class="input-group-prepend">
      <input class="form-control" type="email" id="email">
    </div>
  </div>
  <button id="nextButton">Next</button>
</form>

CodePudding user response:

In keyup function Replace

let checkUsername = $(this).val($(this).val().toLowerCase());

With

let checkUsername = $(this).val($(this).val().toLowerCase()).val();
  • Related