1

I am using bootstrap3 form with jquery/javascript to validate input. This was taken from here

Here is part of my form:

<form id="contact-form" action="#" class="form-horizontal">
<fieldset>

<div class="form-group">
<label class="sr-only" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="name" id="name" placeholder="Your Name">
</div>
</div>

<div class="form-group">
<label class="sr-only" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge form-control" name="email" id="email" placeholder="Email">

Here is the javascript:

 <script>
 $(document).ready(function(){

jQuery.validator.setDefaults({
    errorClass: "help-block"
});
    $('#contact-form').validate({
    rules: {
      name: {
        minlength: 3,
        regex: "/^[A-Za-z\']*$/",
        required: true
      },
      email: {
        required: true,
        email: true
      },
      subject: {
        minlength: 2,
        required: true
      },
      message: {
        minlength: 2,
        maxlength: 400,
        required: true
      }
    },
        highlight: function(element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function(element) {
            element
            .text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
        }
    });
}); // end document.ready
</script>    

The required field and number of digits work wonderfully well. I also intend to add further validation, for example, accept alphabets in name field. I have tried using regex but does not seem to be working.

  1. how to use regex (or multiple) validation in this type of javascript validation ?
  2. how to give appropriate error message when a field has multiple validations (only alphabets and more than 3 characters) ?

I am very new to web development, so these might appear noob questions. Just getting hands on html now. Please guide in right direction.

user3017186
  • 167
  • 3
  • 13
  • [Regex validation](http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation) – tilda Feb 05 '14 at 08:37

1 Answers1

0

For email you should add something like this:

$.validator.addMethod("email", function(value, element) {
          return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
    }, "Invalid email address");

then rules for email should be:

email: "required email",    
blagi
  • 26
  • 4