skip to Main Content

I’m creating a validation on input fields. Its validation is a "8 Characters minimum" and "only contains a combination of letters and numbers".

I’ve made the script as below but it’s still not what I want. Currently, the errors that appear are one by one, not all at once.

For example, if I type "a12" it should show a "8 characters minimum" error. and if I type "a12." or "a12@" , the "8 character minimum" error will disappear and only show "only contains a combination of letters and numbers" error.

The error should be 8 character minimum, only contains a combination of letters and numbers

how to solve this?

$("[name='testing']").on('keyup', function(){
  const getValue = $(this).val();
  const numbers = /^[A-Za-z0-9]*$/;
  
  if(getValue.length < 8){
    $('.error').html('<span class="min-char">8 character minimum</span>')
    
    if(getValue.match(numbers)){
      $('.error .combine-pass').remove()
    }else{
      $('.error').html('<span class="combine-pass">Combination of letters and numbers</span>')
    }
    
  }else{
    $('.error .min-char').remove()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" name="testing">
<div class="error"></div>

2

Answers


  1. I used regular expression validation and javascript event listeners to implement the use case.

    const element = document.getElementById("input");
    element.addEventListener("input", validate);
    
    function validate(e) {
      let value = e.target.value
      const regEx = /^[A-Za-z0-9]*$/
      if (!regEx.test(value) && value.length < 8) {
        document.getElementById("errorMsg").innerHTML = "8 character minimum, only contains a combination of letters and numbers";
      } else if (!regEx.test(value)) {
        document.getElementById("errorMsg").innerHTML = "only contains a combination of letters and numbers";
      } else if (regEx.test(value)) {
        if (value.length < 8) {
          document.getElementById("errorMsg").innerHTML = "8 characters minimum";
          return
        }
        document.getElementById("errorMsg").innerHTML = "";
      }
    
    }
    <input type="text" id="input">
    <div id="errorMsg"></div>

    Please upvote if you find this answer useful.

    Login or Signup to reply.
  2. If you want to check input text contains special character/s then use regex: rg1 = /[^a-z0-9]/gi.

    If you want to check input text contains exactly 8 charcters (letters & numbers) then use regex: rg2 = /^[a-z0-9]{8}$/gi

    using this two regex you can clearly validate your input and so output accordingly.

    if(rg1.test(txt)) return "only contains a combination of letters and numbers";
    else if(!rg2.test(txt)) return "8 characters minimum";
    

    Don’t require the length validation. If the input text length is exactly 8, then rg2 return true otherwise false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search