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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17034666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:51:11  来源:igfitidea点击:

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

javascriptjqueryhtmlvalidation

提问by kine

I am trying to create one of those standard new password forms, where you type the new password once and then a second time to confirm. I would like it so that once you blur away from these fields, if they don't match, bothwill be marked invalid, as in the following scenario:

我正在尝试创建其中一种标准的新密码表单,您可以在其中输入一次新密码,然后再次输入以进行确认。我希望这样,一旦您模糊了这些字段,如果它们不匹配,则两者都将被标记为无效,如下例所示:

  1. User enters password abcinto #newpassword1.
  2. User tabs to #newpassword2.
  3. User enters password definto #newpassword2.
  4. User tabs away.
  5. Validation detects a mismatch, and marks both #newpassword1and#newpassword2as invalid.
  1. 用户输入密码abc#newpassword1.
  2. 用户选项卡到#newpassword2.
  3. 用户输入密码def#newpassword2.
  4. 用户标签离开。
  5. 验证检测不匹配,和标记都#newpassword1#newpassword2为无效。

I know that i can mark the target of an event as invalid by using e.target.setCustomValidity(...), but i don't understand JavaScript's event model very well and can't figure out how to mark a differentelement as invalid based on the event target's own invalidity.

我知道我可以使用 将事件的目标标记为无效e.target.setCustomValidity(...),但我不太了解 JavaScript 的事件模型,并且无法弄清楚如何根据事件目标自身的无效性将不同的元素标记为无效。

This is the relevant excerpt 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);
}

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

从直觉上看,这似乎应该起作用,但当然不是。错误很简单TypeError: $(...).setCustomValidity is not a function

Please note: I am not asking how to add a red ring or whatever to a field, i want it to actually beinvalid (as in, have its validity.validproperty return false).

请注意:我不是在问如何向字段添加红环或其他任何内容,我希望它实际上无效的(例如,让它的validity.valid属性返回false)。

Is it possible to do this?

是否有可能做到这一点?

Thanks!

谢谢!

回答by Sandeep

Try the below code. You are getting that error because jQuery returns an array of selected objects and since setCustomValidityis supported by native input elements and not jquery objects, you are seeing that error.

试试下面的代码。您收到该错误是因为 jQuery 返回一个选定对象的数组,并且由于setCustomValidity本机输入元素而不是 jquery 对象支持,您会看到该错误。

$('#newpassword1, #newpassword2').each(function() {
    this.setCustomValidity(errorMessage)
});

回答by user8012966

<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();

                    }


            })


        });