killkrazy
killkrazy

Reputation: 127

Input Validation on the go

I want to validate a year in the form (XXXX) after the user enters 4 digits into the box, once the user has entered 4 digits I want to have that value so I can pass it to an ajax call.

<h6>What year was the car manufactured</h6>
<input name="car_year" type="text">
<div class="car_make_error car_year_error">Car Year Error</div>

jquery:

$("input[name='car_year']").change(function() {
    validate to make sure 4 digits are in the proper range and get the value of the
    4 digits
}

I know I could use key up but I was not exactly sure how any help would be appreciated.

EDIT

I've used this code:

  $(car_year).keyup(function() {
    var year = $(this).attr('value');
    $('.car_year').html(year);
 });

Upvotes: 1

Views: 220

Answers (2)

Mattis
Mattis

Reputation: 5096

Something like this:

$('#car_year').keyup(function() {
    var year = parseInt($(this).attr('value')); // parseInt forces the value to int
    var min = 1965;
    var max = 2011;
    if (year <= max && year >= min) {
        // Will only go in here if it is an four digit integer between min and max
        $('#result').html('Yeah, looks ok!');
    } else {
        $('#result').html('Not a proper year...');
    }
});

And..

Upvotes: 1

attack
attack

Reputation: 1523

Looks like you were already on the right track. Is this what you need?

$(function() {

    var LOWER_RANGE = 2000;
    var UPPER_RANGE = 2020;

    var $carYearInput = $('#car_year');

    $carYearInput.keyup(function() {
        var value = $carYearInput.val();

        // Check that we were given 4 numbers
        if(value.match(/^[0-9]{4}$/))
        {
            // Convert the value to an int
            var year = parseInt(value, 10);

            // Check that the year is in range
            if(year > LOWER_RANGE && year < UPPER_RANGE)
            {
                alert(year);
            }
        }
    });

});

Upvotes: 2

Related Questions