javascripthtmljqueryvalidationconstraint-validation-api

How can I fix these setCustomValidation unbind issues with my jQuery code


I am using the built-in HTML validation methods to validate the date of birth in a form.

The form has three select list elements:

All three elements have been put as "required" for validation as the user has to select a valid option.

After the user fills out all three options, HTML validation for selecting at least an option goes through fine. Buit I want to check the date for leap year and also make sure user the does not select something like 31st Feb 1998.

Here is my code to do that:

$('#form-signup-next').submit(function(){                       
   if($('#user_dob_month').val()=='2' && $('#user_dob_date').val()>29 ){
        var obj=$('#user_dob_date')[0];
        alert($('#user_dob_month').val());
        obj.setCustomValidity('Invalid Date!');         
   }else{
        var obj=$('#user_dob_date')[0];
        obj.setCustomValidity('');
    }
    return false;
    });

There are several issues


Solution

  • You should not do that on submit of the form because once the setCustomValidity value is set it will not allow to submit the form until unless that validation error value got clear and in your code the issue is that you are clearing the error value on submit. So that's the reason that you are getting the validation error even if you corrected the value on next run.

    For details please check this link CURRENT IMPLEMENTATION ISSUES AND LIMITATIONS(specially Problem 3)

    ok so now you can do this in this way..by checking & setting the error message on drop down value change event

    $('#user_dob_date,#user_dob_month').on('change',function(){
        if($('#user_dob_month').val()=='2' && $('#user_dob_date').val()>29){
        $('#user_dob_date')[0].setCustomValidity('Invalid Date!');
        }
        else{
        $('#user_dob_date')[0].setCustomValidity('');
        }
      });
    

    i checked this & it is working fine.

    So now when a user select the wrong combination & press submit button it will show the error message.

    Try this at http://jsbin.com/aqicim/1