Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation in jQuery without using plugin

I want to perform client-side validation of a simple form using jQuery, but I can't use any plugins for validation. I want to display any error messages in a single alert box.

This is my form:

<form action="" method="post" class="a">
    Name : <input type="text" class="text" name="name" id="name" /> <br/>
    Address : <input type="text" class="text" name="address" id="address" /> <br/>
    Email: <input type="text" class="text" name="email" id="email" /> <br/>

    <input type="button" id="submit" value="Submit" name="submit" />
</form>

If a user submits the form without filling any inputs then I need to display 3 error messages in single alert box. Like this

Name can not be empty.
Address can not be empty.
email can not be empty.  

If only one or two fields remain empty, then I need to control error message according the situation.

Here I tried it using jQuery. But the alerts display in separate boxes:

My jQuery:

$('#submit').on('click', function() {
    valid = true;   
    if ($('#name').val() == '') {
        alert ("please enter your name");
        valid = false;
    }

    if ($('#address').val() == '') {
        alert ("please enter your address");
         valid = false;
    }    
});

Here is a fiddle.

Can anybody tell me how can I figure this out? Thank you.

like image 345
TNK Avatar asked Aug 13 '13 13:08

TNK


People also ask

Does JQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

What is JQuery validate unobtrusive?

Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js.

Can JavaScript be used to validate forms?

HTML form validation can be done by JavaScript.


1 Answers

Loop through each input element in the form, and check if it has a value. If not append the error message to a string which you later alert out if valid is false.

$('#submit').on('click', function() {
    var valid = true,
        message = '';

    $('form input').each(function() {
        var $this = $(this);

        if(!$this.val()) {
            var inputName = $this.attr('name');
            valid = false;
            message += 'Please enter your ' + inputName + '\n';
        }
    });

    if(!valid) {
        alert(message);
    }
});

Fiddle: http://jsfiddle.net/WF2J9/17/

like image 78
ninja Avatar answered Nov 13 '22 08:11

ninja