0

I need to array through all the input elements within a form to check if they are left empty (validation is also on the server). Mootools is being used a library for the site so here is my code:

$$('#emeraldForm input').addEvent("submit",function(){
    //form validation

});

I would like to do that before the form gets submitted. The empty ones will than be given an error classes which will be removed on 'keyup' event.

See full code here

2 Answers 2

1

If you don't want to use HTML5 required attribute or Mootool's More validation providers (inline validation) than you can do something simple like assigning all required input[type=text] elements and input[type=checkbox] elements

class="required" 

and then do something like this:

$('emeraldForm').addEvent("submit",function(evt){
    var preventSubmission = false;
    $(this).getElements("input[type=text].required").each(function(elem) {
        if (elem.get("value").trim() == "") { 
            elem.addClass("error");                
            preventSubmission = true; 
        }
    });
    $(this).getElements("input[type=checkbox].required").each(function(elem) {
        if (!elem.get("checked")) { 
            elem.addClass("error");                
            preventSubmission = true; 
        }
    });
    if (preventSubmission) {
        evt.preventDefault();
    }
});

I am adding class error which can be in CSS specified as red background or some icon next to input element or similar attention drawing thing.

Sign up to request clarification or add additional context in comments.

Comments

0

If can live with HTML5 compatible website only. Then you set the "required" attribute in the input field. There will be no need of client side or server side validation. All the HTML5 compatible browsers will do it for you. Here is some sample code:

<input  name="url" placeholder="Input Example" type="text" required>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.