Javascript 带有输入掩码的 jQuery 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32581404/
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-08-23 10:39:17  来源:igfitidea点击:

jQuery validation with input mask

javascriptjquerytwitter-bootstrapvalidationmasking

提问by D. Cichowski

Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.

有这个问题,带有指定掩码(作为占位符)的表单输入未被 jQuery 验证验证为空。

I use:

我用:

Some strange behaviors:

一些奇怪的行为:

  1. Inputs with attribute requiredare validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)
  2. When i write something into input field and then erase it, I get requirederror message
  1. 具有属性的输入required被验证(由 jQuery)为非空,因此有效,但另一方面,输入不被视为“非空”,也不会检查其他验证规则(这是由validator.js)
  2. 当我在输入字段中写入内容然后将其擦除时,我收到required错误消息

Can anyone give me some hint?

谁能给我一些提示?

EDIT: Relevant code:

编辑:相关代码:

HTML/PHP:

HTML/PHP:

<form enctype="multipart/form-data" method="post" id="feedback">
    <div class="kontakt-form-row form-group">
        <div class="kontakt-form">
            <label for="phone" class="element">
                phone<span class="required">*</span>
            </label>
        </div>
        <div class="kontakt-form">
            <div class="element">
                <input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php">
            </div>
        </div>
        <div class="help-block with-errors"></div>
    </div>
</form>

JS:

JS:

$(document).ready(function() {

    $('#phone').inputmask("+48 999 999 999");

    $('#feedback').validator();      
}); 

采纳答案by D. Cichowski

It's not exactly the solution, but...

这不完全是解决方案,但是...

changing inputmask for some equivalent solves the problem.

更改某些等效的输入掩码可以解决问题

Still far from perfect, though : (

尽管如此,仍然远非完美:(

EXPLANATION:

解释:

Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.

其他屏蔽库,没有提到这两个奇怪的行为,所以可以验证字段。

I used: https://github.com/digitalBush/jquery.maskedinput

我用过:https: //github.com/digitalBush/jquery.maskedinput

回答by Antoine Robin

I managed to use the RobinHerbots's Inputmask (3.3.11), with jQuery Validate, by activating clearIncomplete. See Input mask documentation dedicated section:

我设法通过激活clearIncomplete将 RobinHerbots 的 Inputmask (3.3.11) 与 jQuery Validate一起使用。请参阅输入掩码文档专用部分

Clear the incomplete input on blur

清除模糊上的不完整输入

$(document).ready(function(){
  $("#date").inputmask("99/99/9999",{ "clearIncomplete": true });
});

Personnaly, when possible, I prefer setting this by HTML data attribute:

Personnaly,如果可能,我更喜欢通过 HTML 数据属性设置它:

data-inputmask-clearincomplete="true"

The drawback is: partial input is erasedwhen focus is lost, but I can live with that. So maybe you too ...

缺点是:失去焦点时部分输入会被删除,但我可以忍受。所以也许你也...

Edit: if you need to add the mask validation to the rest of your jQuery Validate process, you can simulate a jQuery Validate error by doing the following:

编辑:如果您需要将掩码验证添加到 jQuery 验证过程的其余部分,您可以通过执行以下操作来模拟 jQuery 验证错误:

// Get jQuery Validate validator currently attached
var validator = $form.data('validator');

// Get inputs violating masks
var $maskedInputList 
    = $(':input[data-inputmask-mask]:not([data-inputmask-mask=""])');
var $incompleteMaskedInputList 
    = $maskedInputList.filter(function() { 
        return !$(this).inputmask("isComplete"); 
    });
if ($incompleteMaskedInputList.length > 0)
{
    var errors = {};
    $incompleteMaskedInputList.each(function () {
        var $input = $(this);
        var inputName = $input.prop('name');
        errors[inputName] 
            = localize('IncompleteMaskedInput_Message');
    });

    // Display each mask violation error as jQuery Validate error
    validator.showErrors(errors);

    // Cancel submit if any such error
    isAllInputmaskValid = false;
}

// jQuery Validate validation
var isAllInputValid = validator.form();

// Cancel submit if any of the two validation process fails
if (!isAllInputValid ||
    !isAllInputmaskValid) {
    return;
}

// Form submit
$form.submit();

回答by Terence

I have the same issue when combined these two libs together.

将这两个库组合在一起时,我遇到了同样的问题。

Actually there is a similar ticket here: https://github.com/RobinHerbots/Inputmask/issues/1034

其实这里有一张类似的票:https: //github.com/RobinHerbots/Inputmask/issues/1034

Here is the solution provided by RobinHerbots:

这是提供的解决方案RobinHerbots

$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});

$("#inputPhone").inputmask("999.999.9999", {showMaskOnFocus: false, showMaskOnHover: false});

The validator assumes that it is not empty when the mask focus/hover is there. simply turn focus and hover of the mask off will fix the problem.

当掩码焦点/悬停在那里时,验证器假定它不为空。只需关闭焦点并关闭遮罩的悬停即可解决问题。

回答by user3089561

I solved this problem with:

我用以下方法解决了这个问题:

phone_number: {
            presence: {message: '^ Prosimy o podanie numeru telefonu'},
            format: {
                pattern: '(\(?(\+|00)?48\)?)?[ -]?\d{3}[ -]?\d{3}[ -]?\d{3}',
                message: function (value, attribute, validatorOptions, attributes, globalOptions) {
                    return validate.format("^ Nieprawid?owa warto?? w polu Telefon");
                }
            },
            length: {
            minimum: 15,
                message: '^ Prosimy o podanie numeru telefonu'
            },
        },