HTML5/JS/jQuery:对于无效的输入,将不同的(任意的)元素标记为无效

HTML5/JS/jQuery: On invalid input, mark a different (arbitrary) element as invalid

本文关键字:无效 任意 记为 元素 输入 于无效 jQuery HTML5 JS      更新时间:2023-09-26

我正在尝试创建一个标准的新密码形式,在那里你输入新密码一次,然后第二次确认。我希望这样,一旦您模糊了这些字段,如果它们不匹配,两个将被标记为无效,如下面的场景:

  1. 用户在#newpassword1中输入密码abc
  2. 用户标签到#newpassword2
  3. 用户在#newpassword2中输入密码def
  4. 用户标签离开。
  5. 验证检测到不匹配,并将#newpassword1 #newpassword2标记为无效。

我知道我可以通过使用e.target.setCustomValidity(...)将事件的目标标记为无效,但我不太了解JavaScript的事件模型,也不知道如何根据事件目标本身的无效将不同的元素标记为无效。

这是我试图使用的(非工作)代码的相关摘录:

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

从直觉上看,这似乎应该工作,但当然不是这样。错误只是TypeError: $(...).setCustomValidity is not a function

请注意:我不是在问如何添加一个红色的环或任何到一个字段,我希望它实际上无效(如在,有它的validity.valid属性返回false)。

这是可能的吗?

谢谢!

试试下面的代码。你得到这个错误是因为jQuery返回一个选定对象的数组,因为setCustomValidity是由本地输入元素而不是jQuery对象支持的,你看到这个错误。

$('#newpassword1, #newpassword2').each(function() {
    this.setCustomValidity(errorMessage)
});
<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();
                    }

            })

        });