HTML5 / JS / jQuery: with invalid input, mark another (arbitrary) element as invalid

I am trying to create one of those standard password forms where you enter a new password once and then a second time for confirmation. I would like that after blurring these fields, if they do not match, both will be marked as invalid, as in the following scenario:

  • The user enters the password abc in #newpassword1 .
  • User Tabs <<22>.
  • The user enters the password def in #newpassword2 .
  • There are no user tabs.
  • The check detects a mismatch and marks both #newpassword1 and #newpassword2 as invalid.

I know that I can mark the event target as invalid using e.target.setCustomValidity(...) , but I am not very well versed in the JavaScript event model and cannot understand how to mark another element as invalid based on the target native invalidation .

This is the corresponding snippet of (non-working) code that I am trying to use:

 if ( $('#newpassword1').val() != $('#newpassword2').val() ) { errorMessage = "The new passwords you've entered don't match."; $('#newpassword1, #newpassword2').setCustomValidity(errorMessage); } 

It seems like this should work, intuitively, but of course not. The error is simply TypeError: $(...).setCustomValidity is not a function .

Please note: I am not asking how to add a red ring or something to the field, I want it to be actually invalid (as in, it has the validity.valid property return false ).

Can this be done?

Thanks!

+6
source share
2 answers

Try the code below. You get this error because jQuery returns an array of selected objects, and since setCustomValidity supported by inline input elements and not jquery objects, you see this error.

 $('#newpassword1, #newpassword2').each(function() { this.setCustomValidity(errorMessage) }); 
+10
source
 <div class="cabinet_settings_header cabinet_header">    </div> <div class="registration_region_select checkbox-group required"> <?for($i = 0; $i < sizeof($regions); $i++):?> <label for="region_id_<?=$regions[$i]['region_id']?>"> <input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" /> <?=$regions[$i]['name']?> </label> <?endfor;?> </div> <div class="cabinet_settings_header cabinet_header">    (  ,   1 )</div> $('.checkbox-group.required input').on('change', function(){ checkRegions(); }); function checkRegions(){ checked_counter = $('.checkbox-group.required :checkbox:checked').length; if(checked_counter > 0){ $('.checkbox-group.required #region_id_2')[0].setCustomValidity(''); }else{ $('.checkbox-group.required #region_id_2')[0].setCustomValidity('  1  '); } } $(document).ready(function() { checkRegions(); $("form").submit(function(event){ if($('.checkbox-group.required :checkbox:checked').length <= 0 ){ $('.checkbox-group.required #region_id_2').focus(); event.preventDefault(); } }) }); 
+1
source

Source: https://habr.com/ru/post/947000/


All Articles