Search code examples
jqueryhtmlwebformspolyfillswebshim

Comparing two text field values to avoid duplicates before submit using Custom validation from webshim


I am using webshim library, I need to compare two text field values to avoid duplicates and want to set custom validation message.

    <form action="sample.html" method="post">
    <label for="country1">Country 1 </label>
    <input type="text" value="" id="country1" name="country1" required/>
    <label for="country2">Country 2 </label>
    <input type="text" value="" id="country2" name="country2" required />
    <input type="button" value="submit" />
    </form>


<script>
  $(document).ready(function(){
    $("#formsubmit").click(function(){
       if($('form').checkValidity()){   
         if($("#country2").val()!= $("#country1").val()){
               $("#country2").addClass('valid').removeClass('invalid')
               $('form').submit();
         }else{
             $("#country2").addClass('invalid').removeClass('valid').setCustomValidity('Please     Enter different country ');
         }
     }
 });

});
</script>    

On Fist time submitting the form if the two text field values are same the Custom validity message get replaced as defined. but when changing the "country 2" value the field remains invalid and form is not getting submitted.

Thanks


Solution

  • Your problem is that you only check those values, if the form is valid. But as soon as you add a custom error you will never be able to submit. Additionally you do not need to submit the form programatically.

    Here you find a a working demo for your problem

    var setCountryValidity = function () {
        var message = 'Please     Enter different country ';
    
        //only test if valid or is invalid because of this validity test
        if ($("#country2").is(':valid') || $("#country2").prop('validationMessage') == message) {
            if ($('#country1').val() != $("#country2").val()) {
                message = '';
            }
    
            $("#country2").setCustomValidity(message);
        }
    };
    
    //test if country1 was changed
    $("#country1")
        .on('change', setCountryValidity)
    ;
    //test if country2 was changed and ...
    $("#country2")
        .on('change', setCountryValidity)
        //... on DOMready
        .each(setCountryValidity)
    ;