SA__
SA__

Reputation: 1862

Custom Validation in Jquery

I have a Validation rule. But i want it to behave in a customized way.

Here is my Rule :

       FirstName:{ 
          required: true,
          minlength:5,
          maxlength:35,
          alphanumeric:true
        }

and Error Message :

      messages: 
      {
      FirstName: "Please enter the First Name"
      }

Here in the Rule if i press Special Character in the First Stroke it will show me the Error Message.

And what ever the mistake i do it will show me the same Error Message.

I want it to behave according to the mistake i do.

i.e.,

If i enter 4 char it should some other Error Message like "Minimum 5 Char"

If i enter more than 35 char it should some other Error Message like "Maximum 35 Char" like this.

How can i do this ?

Update as geeks needs the JS in Full Form :

<script>
var jq = $.noConflict();
jq(document)
    .ready(function () {
            jq("#data")
                .validate({
                        rules: {
                            FirstName: {
                                required: true,
                                minlength: 5,
                                maxlength: 35,
                                alphanumeric: true
                            },
                            messages: {
                                CompID: "Please choose any Company"
                            }
                        })

                    jq('#driver')
                    .click(function () {
                        jq("#data")
                            .valid();
                    });
                });

Upvotes: 0

Views: 77

Answers (1)

Parth Akbari
Parth Akbari

Reputation: 651

Something Like this.

Replce "rangelength" as per your Requriment. JS

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
 });
$( "#myform" ).validate({
   rules: {
   field: {
   required: true,
   rangelength: [2, 6]
   }
 }
});

HTML

<form id="myform">
<label for="field">Required, minium length 2, maximum length 6: </label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">

For your Restict Special Char.

    var specialKeys = new Array();
         specialKeys.push(8); //Backspace
         specialKeys.push(9); //Tab
         specialKeys.push(46); //Delete
         specialKeys.push(36); //Home
         specialKeys.push(35); //End
         specialKeys.push(37); //Left
         specialKeys.push(39); //Right
         function IsAlphaNumeric(e) {
        var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
            var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) ||                    (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode !=   e.keyCode));
         document.getElementById("error").style.display = ret ? "none" : "inline";
          return ret;

Upvotes: 1

Related Questions