1

I'm trying to find a quick and easy way to validate some inputs with jquery. I just need to make sure that a field excepts only numerical values and only 4 integers long, basically a year.

I want to do this with jquery and can't find just a simple solution. I'm guessing you use filter?

$(document).ready(function() $(input#year).filter( ) )};
0

2 Answers 2

2

There are a number of different validation plugins out there that can help with this. The first question you need to ask is whether you want to validate on keypress or on blur. If you choose blur and you must roll your own it would be something like this:

$(document).ready(function() {

   $('#year').blur(function() {
       var match = /\d{4}/.exec(this.value);
       if (!match) {
           alert('invalid');
       }
   }); 

}); 

I would also recommend using the class="year" or $('.year') instead of id or $('#year')

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

Comments

0

You could use a simple plugin that allow only NUMERIC character and add maxlength="4" so the user can't type more char.

You would use it as follow:

$(document).ready(function() {
 $(input#year).numeric() ;
)};

http://www.texotela.co.uk/code/jquery/numeric/

hope this help!

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.