federicot
federicot

Reputation: 12341

Display a warning with jQuery

I'm doing some jQuery form validation and I came up with an issue. I have the following code so far:

// catch any form submission
$('form').submit(function () {
    'use strict';
    // if the browser doesn't support HTML5's required attribute
    if (!Modernizr.input.required) {
        // catch any field that should be required
        $(this).find('input[required]').each(function () {
            // if is empty
            if ($(this).val() === '') {
                // create a span that contains a warning to the user
                var requiredFieldWarning = document.createElement('span');
                requiredFieldWarning.text = 'This field is required.';

                // display the span next to the current field
            }
        });
    }
});

I'm trying to "attach" or display a span next to any input of the submitted form that doesn't validate, but I don't know how to. I want to do this unobtrusively, that's why I create the said span inside JavaScript.

Also, how can I prevent the form from being submitted if any of the fields of the submitted form doesn't validate?

Upvotes: 3

Views: 5686

Answers (4)

mkoryak
mkoryak

Reputation: 57958

why reinvent the wheel? you should use the jquery form validation plugin..

edit: added code to prevent submition of invalid form.

to answer your question:

$('form').submit(function (e) {
    'use strict';
    var valid = true;
    var $form = $(this);
    $form.find("span.error").remove();
    // if the browser doesn't support HTML5's required attribute
    if (!Modernizr.input.required) {
        // catch any field that should be required
        $form.find(':input[required]').each(function () {
            // if is empty
            var $this = $(this);
            if ($.trim($this.val()) === '') {
                // create a span that contains a warning to the user
               $this.after("<span class='error'>This field is required.</span>");
               valid = false;
            }
        });
    }
    if(!valid){
       e.preventDefault();
    }
});

here is a shorter version:

$('form').submit(function (e) {
   'use strict';
    Modernizr.input.required ? e[$(this).find("span.error").remove().end()
        .find(':input[required][value=""]')
        .after("<span class='error'>This field is required.</span>")
        .length ? 'preventDefault': 'isDefaultPrevented']() : null;
});

Upvotes: 2

iambriansreed
iambriansreed

Reputation: 22241

I am adding a span tag after the input. Before the form is revalidated it removes these spans and recreates only if needed. If any of these spans are added the form isn't submitted.

$('form').submit(function (event) {
    'use strict';

    $('.invalid-error', $(this)).remove();
    // remove any old spans

    var submit_form = true;
    // form submits by default

    // if the browser doesn't support HTML5's required attribute
    if (!Modernizr.input.required) {
        // catch any field that should be required
        $(this).find('input[required]').each(function () {
            // if is empty
            if ($(this).val() === '') {  

                $(this).after('<span="invalid-error">This field is required.</span>');
                // add span after input
                submit_form = false;

            }
        });
    }
    if(!submit_form) event.preventDefault();
    // stop form from submitting
});

Upvotes: 1

coolguy
coolguy

Reputation: 7954

 var flag = 0;
 if ($(this).val() === '') {
       flag = 1;
       var warningblock = '<span class="warning">This field is required.</span>';
       $(this).after(warningblock);             
    } 
//end of each loop
if(flag){ //put this block out side the loop
 return false; //form wont submit
}
return true;

    CSS
    .warning{
    /**add styles for warning here***/
    }

Upvotes: -1

Jonathan Payne
Jonathan Payne

Reputation: 2223

jsFiddle ( http://jsfiddle.net/4KxzB/10/ )

Here is my working example, works as expected in chrome.

To stop the form from submitting, just return false;

<form>
    <input type="text" required/>
    <input type="submit" value="submit"/>
</form>

<script>
    $('form').submit(function ()
    {
        'use strict';
        // if the browser doesn't support HTML5's required attribute
        if (!Modernizr.input.required)
        {
            var validInput = true;

            // catch any field that should be required
            $(this).find('input[required]').each(function ()
            {
                // if is empty
                if ($(this).val() === '')
                {
                    // create a span that contains a warning to the user
                    var requiredFieldWarning = document.createElement('span');
                    requiredFieldWarning.text = 'This field is required.';

                    // Cancels form submit
                    validInput = false;
                }
            });

            return validInput;
        }
    });
</script>​

Upvotes: -1

Related Questions