Toskan
Toskan

Reputation: 14931

Simple javascript validation that stops user from submitting form when entering invalid date format?

I am looking for this now quite a while, but did not get good enough answers.

The jquery validation engine is flawed imho. Using the class attribute to place validation rules seems backwards.

I want something super lightweight that:

Displays a small error message as well stops the user from submitting the form.

The error that the user does is the following. He tabs into the date field, then enters manually a wrong format, then submits the form.

See this fiddle

Code:

    <input id="first" type="text" value="" /> 
 <input id="hello" type="text" value="234.12.1984" />



$("#hello").datepicker();

$("#first").focus();

Upvotes: 0

Views: 1363

Answers (2)

Adam
Adam

Reputation: 6733

Add an (initially hidden) error message (say with id "error") and try soemthing like the following:

$('form').submit(function(event){
    try{
        var d = $('#hello');
        $.datepicker.parseDate(d.datepicker( "option", "dateFormat" ), d.val());
    }catch(e){
        event.preventDefault();
        $('#error').show();
        return false;
    }
});

(Maybe with a class/id to say which form of course). Working fiddle

Edit

In response to OP's comment that valid dates missing a leading zero on day/month were then accepted, my suggestion would be simply to fix such dates. I think it is more user-friendly than throwing an error on a valid date. For example, change the try block to

var format = d.datepicker( "option", "dateFormat" );
var tmp_date = $.datepicker.parseDate(format, d.val());
d.val( $.datepicker.formatDate(format, tmp_date) );

I have an updated fiddle where I also added extra code to log the data that would be submitted to the console to show it (I added a name to the input so it would submit the data).

Upvotes: 1

Bhavik
Bhavik

Reputation: 4894

Working Fiddle

<input type="text" class="date" pattern="\d{1,2}/\d{1,2}/\d{4}" placeholder="using pattern" title="dd/mm/yyyy or mm/dd/yyyy"/>  

The only pattern it recognizes is dd/mm/yyyy or mm/dd/yyyy


Update
This answer might help you.


Hope it helps..!

Upvotes: 1

Related Questions