skip to Main Content

I have the following input box:

           <input id="address1"  class="work" />Address1
           <input id="address2"  class="work" />Address2
<input style="float: right; margin-bottom:20px" type="submit" id="myBtn" value="Submit" class="btn btn-primary"  />

I dont want user to type only digits in the input box. I want them to type both digits and alphabets. If the user only type digits then an error is raised when the user clicks on the submit button.

4

Answers


  1. You can use pattern:

    <input id="address1" pattern="[A-Za-z0-9]*[A-Za-z]+[A-Za-z0-9]*" class="work" />Address1
    <input id="address2" pattern="[A-Za-z0-9]*[A-Za-z]+[A-Za-z0-9]*" class="work" />Address2
    
    Login or Signup to reply.
  2. Please try this. This only accept alphanumeric characters in the input box

    <input id="address1"  class="work"  onkeyup="this.value=this.value.replace(/[^A-z0-9]/g,'');"/>Address1
    <input id="address2"  class="work"  onkeyup="this.value=this.value.replace(/[^A-z0-9]/g,'');"/>Address2
    Login or Signup to reply.
  3. ^.*[a-zA-Z].*$ – this pattern seems to work for you:

    <form>
      <label>
        <input pattern="^.*[a-zA-Z].*$" required>
        Address1
      </label>
      <label>
        <input pattern="^.*[a-zA-Z].*$" required>
        Address2
      </label>
      <input type="submit" value="Submit">
    </form>
    Login or Signup to reply.
  4. To make some validation before submitting the form when clicking input[type="submit"], you can do this with .click() and return it with false. This way will block submit event and possibly display any errors if exists. Then, put this regex

    /d.*[a-zA-Z]|[a-zA-Z].*d/
    

    as validation to get both numbers and alphabets in a string.

    $('#myBtn').click((e)=>{
      let a1 = $('#address1');
      let a2 = $('#address2');
      let regex = /d.*[a-zA-Z]|[a-zA-Z].*d/;
      let errors = [];
      for(let a of [a1,a2]) {
        if(!regex.test(a.val())) {
          errors.push(a.attr('id') + ' does not contain both numbers and alphabets!');
        }
      }
      if(errors.length) {
        $('#errors').html(errors.join('<br />'));
        return false;
      }
    });
    #errors {
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form>
      <input id="address1"  class="work" />Address1
      <input id="address2"  class="work" />Address2
      <input style="float: right; margin-bottom:20px" type="submit" id="myBtn" value="Submit" class="btn btn-primary"  />
      <span id="errors" style="float: left; margin-bottom:20px"></span>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search