1

I have a form in bootstrap 3. I am able to do basic validation with the has-error class. How do l check for specific user inputs like?

  1. The user can only enter characters as first name and last name
  2. The user can only enter numbers /digits as telephone number
  3. The user can only enter valid email characters.

And also how can l output a more user friendly validation error messages. I'm new to bootstrap and any help is greatly appreciated. Here is my code

 <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link href="css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

  <form method="post" id="contactform" action="" role="form">
    <div class="form-group">

      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
        glyphicon-user"></span></span>
        <input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
      </div>
    </div>

    <div class="form-group">

      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
        glyphicon-user"></span></span>
        <input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
      </div>
    </div>

    <div class="form-group">

      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
          glyphicon-envelope"></span></span>
        <input class="form-control" placeholder="Email" name="email" type="text" id="email" />
      </div>
    </div>

    <div class="form-group">

      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
          glyphicon-earphone"></span></span>
        <input class="form-control" placeholder="Phone Number" name="phone" type="text" id="phone" />
      </div>
    </div>

    <button type="button" id="contactbtn" class="btn btn- 
    primary">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
  </script>

  <script src="js/bootstrap.min.js"></script>


  <script type="text/javascript">
    function validateText(id) {

      if ($("#" + id).val() == null || $("#" + id).val() == "") {
        var div = $("#" + id).closest("div");
        div.addClass("has-error");
        return false;

      } else {

        var div = $("#" + id).closest("div");
        div.removeClass("has-error");
        return true;
      }
    }

    $(document).ready(
      function() {
        $("#contactbtn").click(function() {

          if (!validateText("firstname")) {
            return false;
          }

          if (!validateText("lastname")) {
            return false;
          }

          if (!validateText("email")) {
            return false;
          }
          if (!validateText("phone")) {
            return false;
          }
          $("form#contactform").submit();
        });
      }
    );
  </script>

</body>

</html>
Priya
  • 1,522
  • 1
  • 14
  • 31

5 Answers5

1

HTML input fields have an attribute called pattern which you can use for ensuring a specific input with a regex.

<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Last Name" name="lastname" 
type="text" id="lastname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Email" name="email" 
type="text" id="email" pattern="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$" />
...
<input class="form-control" placeholder="Phone Number" name="phone" 
type="text" id="phone" pattern="^\d*$" />

That's just a simple sample e-mail regex. There are lot of other regex for e-mails.

Kokogino
  • 984
  • 1
  • 5
  • 17
0

You can use jquery boostrap validation.It's much easy.you can follow following answer

0

You might have to tweak things if you want to use something else. But this is preferably used in bootstrap way.

var showErrorSuccess = function(element, status) {
  if (status === false) {
    element.parent().next().removeClass('hidden').parent().addClass('has-error');
    return false;
  }
  element.parent().next().addClass('hidden').parent().removeClass('has-error').addClass('has-success');
};

var validate = function() {
  event.preventDefault();
  //validate name
  var name = $('#firstname').val();
  if (name.length < 3) {
    return showErrorSuccess($('#firstname'), false);
  }
  showErrorSuccess($('#firstname'));

  var lastname = $('#lastname').val();
  if (lastname.length < 3) {
    return showErrorSuccess($('#lastname'), false);
  }
  showErrorSuccess($('#lastname'));

  //validate email
  var email = $('#email').val(),
    emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
  if (!emailReg.test(email) || email == '') {
    return showErrorSuccess($('#email'), false);
  }
  showErrorSuccess($('#email'));

  //validate phone
  var phone = $('#phone').val(),
    intRegex = /[0-9 -()+]+$/;
  if ((phone.length < 6) || (!intRegex.test(phone))) {
    return showErrorSuccess($('#phone'), false);
  }
  showErrorSuccess($('#phone'));
};
body>form {
  padding-left: 15px;
  padding-top: 15px;
  padding-right: 15px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
  <form class="form-vertical" method="post" id="contactform" onSubmit="javascript:validate()" action="" role="form">
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
      </div>
      <p class="help-block hidden">Please enter a name 3 characters or more.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
      </div>
      <p class="help-block hidden">Please enter a name 3 characters or more.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-envelope"></span></span>
        <input class="form-control" name="email" placeholder="Email" type="email" id="email" />
      </div>
      <p class="help-block hidden">Please enter a valid email address.</p>
    </div>
    <div class="form-group">
      <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-earphone"></span></span>
        <input class="form-control" name="phone" placeholder="Phone Number" type="phone" id="phone" />
      </div>
      <p class="help-block hidden">Please enter a valid phone number.</p>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>
Priya
  • 1,522
  • 1
  • 14
  • 31
  • I tried the code above and l'm not getting any validation. I'm guessing it has to do with the js code. I tried placing the js code in the head section and also tried it right before the closing body tag still no luck. What is the right way to go? – Jim Adjei-Wiredu Mar 27 '18 at 23:05
  • Removed the functions out of $(document).ready(). Now its working. Other way is instead of calling method in html `onSubmit=xyz()` you can bind the method to element with `.on()` of jquery. – Priya Mar 29 '18 at 02:28
  • thanks a lot. The code is now working, l will tweaking it a bit to add more but you definitely showed me the way. – Jim Adjei-Wiredu Mar 30 '18 at 12:49
0

A combination of using the correct input type as well as declaring a pattern attribute can likely preclude the need for any special JavaScript.

1) The user can only enter characters as first name and last name

For this you need to rely on <input type="text"> which by default allows basically anything. So we'll need to apply a pattern that restricts this field to only letters:

<input type="text" pattern="[A-Za-z]+">

2) The user can only enter numbers /digits as telephone number

Depending on your needs this could be as simple as using the correct input type:

<input type="tel">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel

Because different countries have different patterns you may want to improve this with the addition of a pattern attribute.

<input type="tel" pattern="^[0-9\-\+\s\(\)]*$">

This will allow your number inputs to be a bit more flexible, accept dashes and parenthesis, allow the user to specify a +DIGIT country code, etc.

3) The user can only enter valid email characters.

Again using the correct input type will greatly simplify your validation efforts:

<input type="email">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email

This is another one that can be a little 'fuzzy' when you're comparing certain input types as it really just looks for handle@domain.extension. You can read more about its specific validation patterns using the above link to Mozilla's developer toolkit.

Robert
  • 6,881
  • 1
  • 21
  • 26
-1

Here is easy and best concept to use form validation by using custom jquery/javascript code

<!DOCTYPE html>
 <html lang="en">
 <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
  <body>

 <form method="post" id="contactform" action="" role="form">
 <div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="First Name" 
    name="firstname" type="text" id="firstname" />
    </div>
</div>

<div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
    glyphicon-user"></span></span>
        <input class="form-control" placeholder="Last Name" name="lastname" 
   type="text" id="lastname" />
    </div>
   </div>

    <div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-envelope"></span></span>
        <input class="form-control" name="email" placeholder="Email"    type="email" id="email" />
    </div>
   </div>

<div class="form-group">

    <div class="input-group">
        <span class="input-group-addon transparent"><span class="glyphicon 
      glyphicon-earphone"></span></span>
        <input class="form-control" name="phone" placeholder="Phone Number" 
     type="phone" id="phone" />
    </div>
</div>

    <button type="button" id="contactbtn" onclick="validateText();" class="btn btn- 
primary">Submit</button>
</form>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> 
 </script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


 <script type="text/javascript">

  function validateText(id){
   //validate name
var name = $('input[id="firstname"]').val();
if (name.length < 3)
{
    alert('Please enter a name 3 characters or more.');
    return false;
}
var lastname = $('input[id="lastname"]').val();
if (name.length < 3)
{
    alert('Please enter a name 3 characters or more.');
    return false;
}

//validate email
var email = $('input[id="email"]').val(),
    emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if(!emailReg.test(email) || email == '')
{
     alert('Please enter a valid email address.');
     return false;
}

//validate phone
var phone = $('input[id="phone"]').val(),
    intRegex = /[0-9 -()+]+$/;
if((phone.length < 6) || (!intRegex.test(phone)))
{
     alert('Please enter a valid phone number.');
     return false;
}
 }

 
 </script>

  </body>
  </html>
Priya
  • 1,522
  • 1
  • 14
  • 31
SantoshK
  • 1,789
  • 16
  • 24