2

I have a textbox in HTML:

<form method="post" id="register-form" novalidate>
  Session:
  <input type="text" name="session" id="session"/>
  <input type='submit' name='add' value='Save'/>
</form>

I want the date I enter in textbox to be between 2000 & 2014 and input like 212, 998 etc. should be rejected. How to validate it in JQuery?

<script>
  $(function() {
    $("#register-form").validate({
      rules: {      
        session: {
          required: true,
        },  
      },
      messages: {
        session: "Please enter year",                       
      },
      submitHandler: function(form) {
        form.submit();
      }
    });
  }); 
</script>

3 Answers 3

2

You should use the "min" & "max" methods of the jQuery plugin like that:

$("#register-form").validate({
    rules: {        
        session: {
            required: true,
            min: 2000,
            max: 2014     
        },  
 },
    messages: {
    session: "Please enter year",                       
    },
    submitHandler: function(form) {
        form.submit();
    }
});

Sources: http://jqueryvalidation.org/min-method http://jqueryvalidation.org/max-method/

Sign up to request clarification or add additional context in comments.

Comments

2

You can custom validation rule like this

$.validator.addMethod("validYear", function(value, element) {
    return ((parseInt(value) > 1999) && parseInt(value) < 2015);
}, "Year should  be between 2000-2014");

And then use this to define the rule

$("#register-form").validate({
    rules: {        
        session: {
            required: true,
            validYear:true
        },  
 },

Js Fiddle Demo

Comments

1

Use range to specify the range.

$("#register-form").validate({

    rules: {        
        session: {
            required: true,
            range:[2000,2014]

        },  

 },

    messages: {
    session: "Please enter year",                       
    },


    submitHandler: function(form) {
        form.submit();
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.