开发者

Display native validation message in JavaScript

I'm currently developing a form which will be powered by HTML5 features and jQuery. One of the things I've been tasked with is ensuring that the native "Please fill in this field" message is still available to browsers which natively support validation.

My setup looks like so:

|----------|
|   FORM   |
|----------|
===BUTTON===

The form has several parts to it, and so the button is global across them all. The form then slides to the next section if complete.

Here is what I have now, this correctly fires the button event to the form and triggers a submit event.

$(".next").click(function() {
    var $incoming = $(".nextPart #" + (currentSlide));
    var incomingID = $incoming.data("cardid");
    var partCode = "form-" + incomingID;

    $("form[name='" + partCode + "']").trigger("submit");
});

$("form").bind('submit', function(event) {
    var goForth = true;

    if(!event.currentTarget.checkValidity()) goForth = false;

    if(!goForth) return false;

    /* Do some stuff with progress bar and more things */

    return true;
});

However, even though the form submit fails, there is no validation message. Is there a way to pragmatically fire this on an element, or have I done something stupid?

For clarific开发者_如何学Pythonation, this is a screenshot of the validation message I am on about.

Display native validation message in JavaScript


instead of event.currentTarget.checkValidity -- do this...

function checkValidity(elem) {
 // check validity here
 // retun true/false
}

and then in your submit handler do this...

if(checkValidity(event.currentTarget)) { ... 

Also, it is generally NOT a good idea to trigger native browser events -- trigger is good for custom events -- if you need to submit the form you can call the submit() method of the form object like this..

$("form[name='" + partCode + "']").get(0).submit();


As I described in my first post, I was using a click event on a button which was in a global scope. This was then sending a submit action to the form which, although was sending the form to be submitted, it wasn't firing the bubble event (whatever the hell that is) on the elements.

To fix this, I wrapped all of my slides in one form instead of multiples. I kept my submit button outside of the slides, so it still acted as a global navigation item.

Removing the click event from this button and changing the type of it to submit now gets the bubble displaying.

Not the best fix, since the bubble should be able to be trigged without having to submit the form, however, I guess with HTML5 validation, you can define the parameters for what is accepted and what isn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜