简体   繁体   English

元素上的自定义表单验证 function html 5

[英]Custom form validation function on element with html 5

For a custom image selection tool I would like to create form validation based on html 5 form validation.对于自定义图像选择工具,我想创建基于 html 5 表单验证的表单验证。

For example my form consists of the following elements:例如我的表单包含以下元素:

<form class="cms-form" action="">
    <table width="800">
        <tr>
            <td width="30%">Name:</td>
            <td><input type="text" name="name" class="cms-input-text" maxlength="127" /></td>
        </tr>
        <tr>
            <td>Image:</td>
            <td><textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{&quot;min&quot;:1,&quot;max&quot;:3}">/location-to-image.png</textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Next"/></td>
        </tr>
    </table>
</form>

I have a Javascript that changes the textarea (.cms-input-file) into some html to add images and hides the original textarea.我有一个 Javascript 将文本区域(.cms 输入文件)更改为一些 html 以添加图像并隐藏原始文本区域。 It looks something like this:它看起来像这样:

<textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{&quot;min&quot;:1,&quot;max&quot;:3}" style="display: none;">/location-to-image.png</textarea>
<ul class="cms-input-file-list">
    <li class="cms-input-file-item" data-image="/location-to-image.png">
        <img src="/location-to-thumb.png" alt="" class="cms-input-file-item-thumbnail"/>
        <span class="cms-input-file-item-title">location to image</span>
    </li>
    <li class="cms-input-file-add">Add</li>
</ul>

Since I have allot of existing forms using html5 form validation I would like to validate this element using the default form validation within html5 supported browsers, but using a hopefully existing event.由于我已经使用 html5 表单验证分配了现有的 forms,因此我想在支持 html5 的浏览器中使用默认表单验证来验证此元素,但使用希望存在的事件。

I'm looking for something like this:我正在寻找这样的东西:

$('.cms-input-file').on('customValidateFunction', function () {
    var options = $(this).data('options');

    if($(this).find('> li.cms-input-file-item').length < options.min)
    {
        return [false, 'Add more images.'];
    }

    if($(this).find('> li.cms-input-file-item').length > options.max)
    {
        return [false, 'Remove some images.'];
    }

    return true;
});

Does anyone know if something like this is possible using default html 5 events or how would I go about adding this event to the submit event?有谁知道使用默认 html 5 事件是否可以实现类似的事情,或者我 go 如何将此事件添加到提交事件? To actually trigger the default browser validation look and feel.实际触发默认浏览器验证外观。

-- edit -- - 编辑 -

So far I have made an attempt to get this result using a div element which hides the original element.到目前为止,我已经尝试使用隐藏原始元素的 div 元素来获得此结果。 But now I need to add a pattern to the element to match according to my options.但是现在我需要向元素添加一个模式以根据我的选项进行匹配。 Is this possible?这可能吗?

Current progress: http://jsfiddle.net/jeffreydev/YyEVu/目前进度: http://jsfiddle.net/jeffreydev/YyEVu/

If I understand correctly what you need, I think you can achieve what you are trying to do using the pattern attribute of any input element.如果我正确理解您的需求,我认为您可以使用任何输入元素的模式属性来实现您想要做的事情。

I've created a very simple form in jsfiddle illustrating this.在 jsfiddle 中创建了一个非常简单的表单来说明这一点。

The idea is that you update the value of your input with whatever data you have in your model when adding or removing images.这个想法是,在添加或删除图像时,您可以使用模型中的任何数据更新输入值。 The example, just adds one letter f per icon.该示例只为每个图标添加一个字母f Then, you can create a regex to match the expected valid results.然后,您可以创建一个正则表达式来匹配预期的有效结果。 In the example, pattern="f{1,3}" means that to be valid, the content can be "f", "ff", or "fff" but nothing else, which means that it'll only accept from one to three files to be sent.在示例中, pattern="f{1,3}"表示要有效,内容可以是 "f"、"ff" 或 "fff" 但没有其他内容,这意味着它只会接受来自一个到要发送的三个文件。

You would be using just default html5 form validation, but you may need a bit of tweaking to get it working.您将仅使用默认的 html5 表单验证,但您可能需要进行一些调整才能使其正常工作。

However, if you try this way, you should keep a couple of things in mind:但是,如果您尝试这种方式,则应记住以下几点:

  1. As explained in the specs , the patttern is compiled as a JavaScript regular expression with the global, ignoreCase, and multiline flags disabled规范中所述,模式被编译为 JavaScript 正则表达式,禁用 global、ignoreCase 和 multiline 标志
  2. Setting the disabled property of your input so that the user can't change it would take it out of the form, and thus it won't be validated设置输入的 disabled 属性以便用户无法更改它会将其从表单中移除,因此不会对其进行验证
  3. Applying certain styles as *display:none" to the input element can cause errors when the validation fails and the browser tries to gain focus on the element.将某些样式作为 *display:none" 应用于输入元素可能会在验证失败并且浏览器试图获得对元素的关注时导致错误。

I hope you this helps我希望你这有帮助

You can install a submit handler on the <form> , and dispatch a custom event from there.您可以在<form>上安装submit处理程序,并从那里分派自定义事件。

That will look something like this:这看起来像这样:

$('form.cms-form').on('submit', function(evt) {
    var frm = $(this);
    var allElements = $(this.elements);
    $('#errors').empty();   

    var errors = [];
    var arg = {
        reportValidationError : function( msg ) {
            errors.push(msg);
        },
        form : this
    };
    console.log("all elements: ", allElements);
    allElements.trigger('customValidate', [ arg ]);

    if( errors.length !== 0 ) {
        showValidationErrors(errors);
        return false;
    }
    return true;
});

Then, you can "hook" the customValidate event, and install your own logic...然后,您可以“挂钩” customValidate事件,并安装您自己的逻辑...

$('textarea[name=icon]').on('customValidate', function(evt, reporter) {
    var options = $(this).data('options');

    // ... your validation here ...

    // for example:
    var txt = $(this).val();
    if( txt.length < options.min || txt.length > options.max ) {
        reporter.reportValidationError('error: "icon" min/max exceeded!');
    }
})

Here's an example at jsFiddle .这是 jsFiddle 的一个例子


Edit编辑

You can style the error reporting, and tweak the code, to look and behave however you want it to.您可以设置错误报告的样式,并调整代码,使其外观和行为随您的需要而变化。 Here's an example .这是一个例子

A very good jquery plugin to validate your forms is Mike Alsup one's.一个非常好的 jquery 插件来验证你的表单是 Mike Alsup 的。 You will find it here: http://jquery.malsup.com/form/你会在这里找到它: http : //jquery.malsup.com/form/

It is documented, ajax compatible.它被记录在案,与 ajax 兼容。

It can do serialization for one field or for all fields inside the form, so it is a big advantage regarding your problem you could need to handle fields validation and error logic with your forms.它可以对表单中的一个字段或所有字段进行序列化,因此对于您可能需要使用表单处理字段验证和错误逻辑的问题,这是一个很大的优势。

You could add the blockUI plugin of the same author to enhance user's experience, and don't have to manage double submission of the form when javascript is enabled.可以添加同一作者的blockUI插件来提升用户体验,不用在启用javascript的情况下管理表单的重复提交。 http://jquery.malsup.com/block/ http://jquery.malsup.com/block/

Answer from 2022: Yes, it is possible without jQuery etc. 2022 年的回答:是的,没有 jQuery 等是可能的。

Most browsers support Constraint Validation API (even IE 11 according to "caniuse")大多数浏览器都支持约束验证 API (根据“caniuse”甚至是 IE 11)

The recommended practice is to listen to input/submit events and then set validity flags on the input-box.推荐的做法是监听input/submit事件,然后在输入框上设置有效性标志。

<form>
    <input type="text" required id="answer">
    <input type="submit">
</form>

Validation JS:验证JS:

const nameInput = document.querySelector("#answer");
const form = document.querySelector("form");

function validate(e) {
  if (nameInput.value == "42") { //correct!
    nameInput.setCustomValidity(""); // empty means "no error"
  }
  else {
    nameInput.setCustomValidity("Wrong answer!"); //show error text
    e.preventDefault(); //prevent form submit
  }
}

nameInput.addEventListener("input", validate);
form.addEventListener("submit", validate);

The input event fires even when the value is changed programmatically即使值以编程方式更改, input事件也会触发

PS Codepen to play with: https://codepen.io/jitbit/pen/XWYZjXO PS Codepen 玩: https://codepen.io/jitbit/pen/XWYZjXO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM