0

I am new to web development and I am trying to create a simple form validation using javascript/jquery.

I drafted a simple form very similar to what I have that looks like this:

<form>
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <button type="submit" onclick='return validateSubmit();'>Save</button>
</form>

What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:

var validateSubmit = function () {
    var inputs = $('.price');
    var errors = 'False';
    for (var i = 0; i < inputs.length; i++) {
        if (isNaN(inputs[i].value)) {
            $('.price')[i].focus();
        }
        errors = 'True';
    }
    if (errors == 'True') {
        alert('Errors are highlighted!');
        return false;
    }
    return true;
};

I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!

1
  • Maybe you should try with some simple JavaScript form validation library like, for example, validate.js or something similar. Commented May 15, 2015 at 1:58

2 Answers 2

1

You can add a class to the inputs with bad values. The class can add a border for example.

var validateSubmit = function () {
  
    var inputs = $('.price');
    var errors = 'False';
   
    for (var i = 0; i < inputs.length; i++) {
        if (isNaN(inputs[i].value)) {
            $(inputs[i]).addClass('error');
            errors = 'True';
        } else {
          $(inputs[i]).removeClass('error');
        }
        
    }
  
    if (errors == 'True') {
        alert('Errors are highlighted!');
        return false;
    }
    return true;
};
.error {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <input class="price" type="text" />
    <br />
    <button type="submit" onclick='return validateSubmit();'>Save</button>
</form>

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

5 Comments

Hi, thank you , the highlighting part is working but can you review the script as to why even after correcting the highlighted textbox it still returns an error after the second submit click
Put condition in else statement inside for loop to remove class for unmatched condition at initial if by using .removeClass() function api.
updated code. The True was always being set and added a removeClass on good inputs when submitted.
@tellez yes thank you it finally worked perfectly. One last thing though, if I wanted to make it a real time validation, I mean as I type it checks if what Im typing is valid, will it be very different to this code or I have to use some external js library to be able to do that? Anyway thank you so much for your answer, very helpful!
@tellez can you also take a look why I cant make it work in js fiddle jsfiddle.net/supermaynard05/oL09t762
0

First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.

<form id="price-form" action="" method="get">
     <input name="price[]" type="text" value="" class="price" />
     <br />
     <input name="price[]" type="text" value="" class="price" />
     <br />
     <input name="price[]" type="text" value="" class="price" />
     <br />
     <input name="price[]" type="text" value="" class="price" />
     <br />
     <button type="submit">Save</button>
</form>

Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?

$(function() {

    $('#price-form').on('submit', function(e) {
        // this variable acts as a boolean, so might as well treat it as a boolean
        var errors = false;
        // remove previous errors 
        $('.price').removeClass('error');
        // check each input for errors
        $('.price').each(function() {
            if (isNaN(this.value)) {
                $(this).addClass('error');
                errors = true;
            }
        });
        // alert if there are any errors
        if (errors) {
           alert('Errors are highlighted!');
           e.preventDefault(); // stop submission
        }
   });
});

In your CSS, you could do

.error {
     border: 2px solid #a00;
}

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.