raju
raju

Reputation: 209

jquery name validation using plugin

I am trying to validate the first name of a user such that it should accept only characters. I also want to assign a maximum length validation, and the first name should not be empty.

But I could get validation only for characters. Now I want to set max length for the first name and name should not be empty also when validation fails it should change the border color of the input box to red and give an error message.

$(document).ready(function(){
  jQuery.validator.addMethod("lettersonly", function(value, element) {
     return this.optional(element) || /^[a-z\s]+$/i.test(value);
  });

  $('#myForm').validate({
    rules: {
        firstName: {
            lettersonly: true

        }
    },
    messages:{
        firstName: {
            lettersonly: "please enter characters only",
        }
    }
  });
});
.error{
   color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>


 <form id="myForm">
   <label for="firstname" id="label1">firstName:</label>
   <input type="text"id="firstName" name="firstName"><br><br>
</form>

Upvotes: 0

Views: 5500

Answers (1)

Martin Jinda
Martin Jinda

Reputation: 488

You can use built-in function in jquery-validation plugin.

https://jqueryvalidation.org/maxlength-method/

Return false if the element is

  • some kind of text input and its value is too long
  • a set of checkboxes that has too many boxes checked
  • a select and has too many options selected

Live demo

$('#myForm').validate({
rules: {
    firstName: {
        lettersonly: true
        required: true,
        maxlength: 200
    }
},
messages:{
    firstName: {
        lettersonly: "please enter characters only",
        required: "Enter your first name, please.",
        maxlength: "Funny msg"
    }
}
});

Upvotes: 3

Related Questions