0

I have this script piece in an javascript function to validate some fields in my form

var situacao = $("select[name='situacaoCRC']").val();
var dta_emissao = $("input[name='dtaEmissao']").val();
var dta_validade = $("input[name='dtaValidade']").val();

if (situacao == -1) {
    alert('Selecione um estado para o CRC.');
return false;
}

if (dta_emissao === undefined || dta_emissao === "") {
    alert('Data de emissão do CRC inválida.');
return false;
}

if (dta_validade === undefined || dta_validade === "") {
alert('Data de validade do CRC inválida.');
return false;
}

if (dta_validade <= dta_emissao) {
    alert('A data de validade do CRC deve ser posterior à data de emissão.');
return false;
}

The fields dta_validade and dta_emissao are both dates in the format DD/MM/YYYY

When i put in this fields, let's say, dta_validade = 01/12/2011 and dta_emissao = 01/01/2012 and, with this data, i get the alert in the 4th IF

0

2 Answers 2

2

You need to create 2 date objects, before you can compare them. You can find some information about it here: http://www.w3schools.com/js/js_obj_date.asp

var test_date1;
test_date = new Date(2011, 11, 1); //Year, Month (zero based), Day 

(In this case you need to parse the values of the year, month and day yourself)

You can also use Datejs to make things easier for you: http://www.datejs.com

Or, seeing as you're already using jQuery, use the jQuery UI Datepicker: http://jqueryui.com/demos/datepicker/

$.datepicker.formatDate( format, date, settings ) 
// Format a date into a string value with a specified format.
$.datepicker.parseDate( format, value, settings ) 
// Extract a date from a string value with a specified format.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the edit Cros, I always forget that Month is indeed zero based (from 0 [January] to 11 [December]).
1

You could change your last last if to:

if (parseDate(dta_validade) <= parseDate(dta_emissao)) {
    alert('A data de validade do CRC deve ser posterior à data de emissão.');
    return false;
}

Then you can add:

function parseDate(s) {
    var a = s.split('/');
    return new Date(parseInt(a[2]), parseInt(a[1])-1, parseInt(a[0])); // month is zero-based
}

Don't forget error handling.

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.