0

Iam not understanding to do validation for the 'FullName' field..

Below are the validations required for the 'FullName' field:

  • only letters a to z (lower case), "-" (dash or hyphen) and " " (space) are allowed,
  • the "-" (dash) AND " " (space) letters MUST be entered,
  • the "-" or the " " letter must not be either the first or the last letter entered,
  • "-" must not be the immediate neighbour or adjacent (before or after) to a " ",
  • "-" or " " must not be the immediate neighbour (adjacent) to itself.


I knew I can do in this way:

$('#fullName').blur(function(){


            var input = $('#fullName').val();
            if(  !/[^a-z0-9 -]/.test(input)  &&     
                 / /.test(input) && /-/.test(input)  &&  
                 !/^[ |-]|[ |-]$/.test(input)  &&      
                 !/ -|- |--|  /.test(input))
            {
                 $('.error').remove();
            }
            else{
                 $('#fullName')
                     .after('<span class="error">Your Name should be entered like:  "blahblah" </span>');
            }

    });

BUT I am not understanding how to insert above regex code into here:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>

<script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

  <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>


 <script>

$(document).ready(function(){


 $("#fullname").focus();

  $("#fullname").addMethod("alphanumeric", function(value, element) {
    return ! $("#fullname").methods.required(value, element) || /^[a-zA-Z0-9_]+$/i.test(value);
} , "Letters, numbers or underscores only please"); 




      $("#ourform").validate({
        onfocusout: function(element) { $(element).valid(); } ,
        rules: {
            fullname : {
              required: true,
              maxlength: 14,
              alphanumeric : false
            },                  
            email: {
              required: true,
              email: true
            }
        },
        messages: {
            fullname : {
              required: "Please specify your Full Name",
              maxlength:  "Please enter only upto 14 characters",
              alphanumeric : "do not enter alphanumeric"
            },
            email: {
              required: "We need your email address to contact you",
              email: "Your email address must be in the format of name@domain.com"
            }
        }
      });



   });



  </script>



<style>

.error {color: red;}

</style>


 </head>

 <body>




<form id="ourform" method="get" action="">

       <fieldset>

           <p>
             <label for="fullname">Full Name</label>
             <em>*</em><input id="fullname" name="fullname" size="25" class="required"  maxlength="14" />
           </p>


           <p>
             <label for="email">Email</label>
             <em>*</em><input id="email" name="email" size="25"  class="required email" />
           </p>



     </fieldset>

  </form>



 </body>
</html>


EDITED: - FullName (both first and family name - use ONE field for both),

Clarsen
  • 125
  • 1
  • 3
  • 9

1 Answers1

1

You have two questions here:

  1. How to validate the full name per your rules.
  2. How to add custom jQuery validator validation rules.

How to add custom jQuery validator validation rules

Here is an example of validating the field has the value "Mark" for fullname:

$(document).ready(function() {
    var fullname_invalid = function(value) {
        return value === "Mark";
    }


    $.validator.addMethod("custom_fullname", function(value, element) {
        return fullname_invalid(value);
    }, 'Your Name should be entered like: "Mark"');

    $('#signup').validate({
        rules: {
            fullname: {
                required: true,
                custom_fullname: true
            }
        }
    });

    $('#signup').on('submit', function(event) {
        event.preventDefault();
    });
});​

HTML:

<form id="signup" action="/action">
    <input name="fullname" type="text" />
    <input type="submit">
</form>​

Demo: jsfiddle

Reference: jQuery Validate Plugin - How to create a simple, custom rule?

How to validate the full name per your rules

$(document).ready(function() {

    var validCharactersRegex = new RegExp(/^[a-zA-Z0-9 -]+$/);
    var doesNotStartWithDashOrSpace = new RegExp(/^[^ -]/);
    var fullname_invalid = function(value) {
        return validCharactersRegex.test(value) && doesNotStartWithDashOrSpace.test(value) && value.indexOf('  ') == -1 && value.indexOf('--') == -1 && value.indexOf(' -') == -1 && value.indexOf('- ') == -1;
    }


    $.validator.addMethod("custom_fullname", function(value, element) {
        return fullname_invalid(value);
    }, 'Your Name should be entered like: "blahblah"');

    $('#signup').validate({
        rules: {
            fullname: {
                required: true,
                custom_fullname: true
            }
        }
    });

    $('#signup').on('submit', function(event) {
        event.preventDefault();
    });
});​

Demo: jsfiddle

Community
  • 1
  • 1
Cymen
  • 14,079
  • 4
  • 52
  • 72
  • Does $.validator.addMethod("alphanumeric" means $("#fullname").addMethod("alphanumeric" ?? – Clarsen Dec 12 '12 at 16:09
  • No. It adds a validation rule to the validator that you can use on any field. You hook it up to a specific field with the `rules` in the `validate` call. It is confusing but try out the demo and play with it. By the way, you should use good rule names for your custom rules. Something like alphanumeric may be too generic. Also you could separate each of your rules for the full name into a separate validation with a more specific error. Or you can keep them all in one big validation method as shown here. – Cymen Dec 12 '12 at 16:20
  • Actually it seems that it takes more time to understand your demos, since first of all iam not aware of Javascript or jquery much.. very new in these both.. Problem is, i do not have suffice time to understand, practise and write on my own.. You seems to be a very experienced on this, If you do not mind, could you please write and send me a code for now..? pls do not think me wrong bro,, and ur very helpful.. what u say..? – Clarsen Dec 12 '12 at 16:53
  • @Clarsen I can't but you can copy and paste from the demos and adapt to your form. Good luck. You can always post more questions if you run into problems. – Cymen Dec 12 '12 at 17:11
  • @clarsen could you please check this: http://jsfiddle.net/ea829/13/ , fullname field not working as per my requirement.. and it also need to check every field validation as 'onblur' – Clarsen Dec 13 '12 at 10:14
  • @Clarsen You don't need to validate manually on blur. jQuery Validation does this already. Try the demo I linked to at the end of my answer. Enter a bad wrong name. Click submit and see the validation error. Fix it and then click off of the field (blur) and see it automatically revalidate. – Cymen Dec 13 '12 at 15:20
  • Bro, as you said, I have tried my best, BUT something went wrong, could you please take ur little time and help me on this: http://jsfiddle.net/ea829/18/ when I click 'submit', nothing happening.. (instead just refreshing, seems something wrong in my code.. pls kindly have a look.. – Clarsen Dec 13 '12 at 17:01
  • @Clarsen I went to your fiddle and opened up the chrome console and saw an error on line 28. It is due to your RegExp not have `//` so I fixed that and it seems to work: http://jsfiddle.net/ea829/19/ You should get used to opening up the console and you should try using Google Chrome (if you're not) as the development tools are really good. – Cymen Dec 13 '12 at 18:19
  • Thanks Bro... But you know iam hitting hard to a wall to do a FullName validation perfectly.. I really hate regex code, since it looks dirty and i dont understand anything.. it looks like a scribbling code... what went wrong in my validation code for 'fullname'? when I just entered as "Roger Federer" in full name field, its showing me error as "your name should be blah blah" and BTW, i just did a small update in my original post.. pls chk it! pls help me achiving this Fullname validation perfecting using regex bro... iam really tired struggling for this as iam very new for this regex, jquery – Clarsen Dec 13 '12 at 18:56
  • @Clarsen My advice is don't use regular expressions you don't understand/test. My answer at the bottom with this jsfiddle has a working validation for fullname: http://jsfiddle.net/ea829/ Note that we use RegExp for some things but `indexOf` for other things. If I paste "Roger Federer" into [that jsfiddle](http://jsfiddle.net/ea829/) it works. – Cymen Dec 13 '12 at 19:03
  • Ok fine! BUT one thing: it should not allow only 1 word, instead the format should be allowed as "fistname lastname" (or) "firstname-lastname" , so how can i achiev this? – Clarsen Dec 13 '12 at 20:53
  • one more thing: In my case, I do not have submit button, so how can i achive validation...? – Clarsen Dec 13 '12 at 20:54
  • last query: how can i achive this as well? - visitor location from a drop-down list which includes the items: South Yorkshire, Rest of England, Wales, Scotland, Northern Ireland, European Union, Rest of World, Other, and which includes an appropriate default, – Clarsen Dec 13 '12 at 20:56
  • @Clarsen Use a `select` tag with those options. The first one will be the default. Or you set a later one as the default by setting the `selected` attribute to `selected`. – Cymen Dec 13 '12 at 21:19
  • Ok fine! BUT one thing: fullname field should not allow only 1 word, instead the format should be allowed as "fistname lastname" (or) "firstname-lastname" , so how can i achiev this? and In my case, I do not have submit button, so how can i achive validation...? – Clarsen Dec 14 '12 at 06:13
  • @Clarsen I didn't put that in because it's not on your validation list. You can add `&& value.indexOf(' ') != -1` to the end of the big line in the `fullname_invalid` function to accomplish that. – Cymen Dec 16 '12 at 02:09
  • I just used this: var validCharactersRegex = /^[a-z][- a-z]*[- ]{2}[- a-z]*[a-z]$/i; Its working perfectly now! (I removed all indexof() .... and thxn for your help bro! :) – Clarsen Dec 17 '12 at 03:13
  • @Clarsen Can you accept the answer if this is working for you? You click the checkmark next to the answer to do so. I'm glad it's working! – Cymen Dec 17 '12 at 04:22
  • I ticked your answer green bro... thnx a lot for ur trying before.. BTW, can u also pls look into this: http://stackoverflow.com/questions/13960406/sidebar-missing-can-anyone-pls – Clarsen Dec 19 '12 at 20:12
  • @Clarsen Thanks. I can't do anything with that question as it looks like it got locked. – Cymen Dec 19 '12 at 21:22
  • can u please look into this site header: articlewritingservicess.com (this is my clients site) menubar hided inside the header.. what changes I have to make? – Clarsen Dec 19 '12 at 21:51
  • this is the actual theme: http://demo2.woothemes.com/?name=emporium I replaced
    blah... blah
    with my 2 images...
    – Clarsen Dec 19 '12 at 21:58