Search code examples
htmltwitter-bootstrap-3

Phone number validation bootstrap3


I am trying to create a form in my website for people to able to put phone number and submit the form. But when I type alphabets instead of numbers, it still accepted. Is there anyway I can check phone validation using Bootstrap 3?

Here is my code

<footer>
  <hr>
  <div class="container text-center">
    <h3>Subscribe for special offer</h3>
    <p>Enter your information</p>

    <form action="" class="form-inline">
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" placeholder="Name" required="required">
      </div>
      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email" placeholder="Email" required="required">
      </div>
      <div class="form-group">
        <label for="phone_no">Phone Number</label>
        <input type="text" name="num" data-validation="number" data-validation-allowing="negative,number" input name="color" data-validation="number" datavalidation-ignore="$" required="required" class="form-control" id="phone_no" placeholder="Phone Number">

      </div>
      <button type="submit" class="btn btn-default">Subscribe</button>
      <hr>
    </form>
    <!--End form-->

    <hr>

  </div>
  <!--End Container-->

</footer>


Solution

  • You can use it using the pattern attribute. You can generate a pattern from this link.

    HTML:

    <form>
      <h2>Phone Number Validation</h2>
      <label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br/>
      <input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required >
    
      <input type="submit" value="Submit">
      <p class="p">Demo by Agbonghama Collins. <a href="http://www.sitepoint.com/client-side-form-validation-html5/">See article</a>.</p>
    </form>
    

    CSS:

    input[type="tel"] {
      border: 1px solid #ddd;
      padding: 4px 8px;
    }
    input[type="tel"]:focus {
      border: 1px solid #000;
    }
    
    input[type="submit"] {
      font-weight: bold;
      padding: 4px 8px;
      border:1px solid #000;
      background: #3b5998;
      color:#fff;
    }
    
    form {
      width: 50%;
      margin: 0 auto;
    }
    
    .p {
      padding-top: 30px;
    }
    

    Fiddle here.