16

For a custom image selection tool I would like to create form validation based on html 5 form validation.

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. 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.

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? 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. 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/

4
  • are you using a jquery form-validation plugin ?
    – unloco
    Aug 23, 2012 at 4:06
  • No, I am only using default html5 browser validation, but am wondering if I can hook into that using javascript for this matter.
    – jeffreydev
    Aug 23, 2012 at 7:12
  • Do you still want that form to be submitted when 1 to 3 images have been added? I still think you can do it with any of the methods shown in the pattern example or the customValidation example posted below. Both do just that.
    – jbalsas
    Aug 28, 2012 at 22:36
  • Didn't think about that yet, I will probably end up hiding the original element using a parent element with height and width of 0 and set overflow to none (this way the popup from the browser still shows), and then using the setCustomValidity function on change instead of when the form submits to display the correct message. Thank you!
    – jeffreydev
    Aug 29, 2012 at 6:29

4 Answers 4

5
+50

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.

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. 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.

You would be using just default html5 form validation, but you may need a bit of tweaking to get it working.

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
  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
  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.

I hope you this helps

2
  • I've added a variation of the example. In this case, it uses setCustomValidity() to do the custom validation for that field. It comes with the benefit of better control over the validation message.
    – jbalsas
    Aug 28, 2012 at 1:49
  • Thank you for your input, this gave me some ideas on how I could maybe hide the original input element instead of using display:none.
    – jeffreydev
    Aug 28, 2012 at 8:20
3

You can install a submit handler on the <form>, and dispatch a custom event from there.

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...

$('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.


Edit

You can style the error reporting, and tweak the code, to look and behave however you want it to. Here's an example.

6
  • Yes, however this doesn't trigger the default validation from the browser, as in it looks allot different then the default browser validation looks. Also it triggers after the default form validation does. As you can see here: jsfiddle.net/jeffreydev/6ZGJu
    – jeffreydev
    Aug 23, 2012 at 18:45
  • [1] You can style the error reporting to look however you want it to. Here's an example. | [2] I'm not sure why it's a problem for the custom validation to run after the HTML5 validation... it all has to run (and pass) before the form will be submitted. Can you elaborate on this concern?
    – Lee
    Aug 23, 2012 at 21:38
  • How annoying is it submitting a form, getting errors because you didn't fill everything in. Then filling those fields in, submitting again and getting more errors.
    – jeffreydev
    Aug 24, 2012 at 9:21
  • On my browser (chrome), that's exactly how the built-in HTML5 validation works: one field at a time. [I see that, on Firefox, the message popup appears for only a single field at a time, but all failed fields get a red border -- is that red border what you're talking about?] Let me know what browser you're using, so I can see the behavior you're trying to produce.
    – Lee
    Aug 24, 2012 at 16:26
  • My main browser is indeed Firefox, I wasn't aware that the way the errors are displayed are different on these browsers. Perhaps I will just have to create / find a plugin which will validate forms according to html standards and add support for a custom validation function. I was hoping this could be avoided. Thank you for your input.
    – jeffreydev
    Aug 27, 2012 at 7:26
1

Answer from 2022: Yes, it is possible without jQuery etc.

Most browsers support Constraint Validation API (even IE 11 according to "caniuse")

The recommended practice is to listen to input/submit events and then set validity flags on the input-box.

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

Validation 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

P.S. Codepen to play with: https://codepen.io/jitbit/pen/XWYZjXO

0

A very good jquery plugin to validate your forms is Mike Alsup one's. You will find it here: http://jquery.malsup.com/form/

It is documented, ajax compatible.

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. http://jquery.malsup.com/block/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.