2

I'm a jQuery newbie, but long-time Perl developer and know regexes well, so I don't want to use the jQuery Validation plugin.

I'm trying to validate the following 3 web forms, each of which has a text or textarea input field #blah_txt and a submit button #blah_btn:

alt text

I'm validating them with the following jQuery code, which seems to work well:

<script type="text/javascript" src="/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function() {
        $('#mks_btn').click(function(e) {
                $('#cl_txt').css('border', '2px solid black');
                $('#comment_txt').css('border', '2px solid black');

                if (! $('#mks_txt').val().match(/^(CL\s*)?[0-9]{6,}$/i)) {
                        $('#mks_txt').css('border', '2px solid red');
                        e.preventDefault();
                }
        });
        $('#cl_btn').click(function(e) {
                $('#mks_txt').css('border', '2px solid black');
                $('#comment_txt').css('border', '2px solid black');

                if (! $('#cl_txt').val().match(/^(MKS\s*)?[0-9]{6,}$/i)) {
                        $('#cl_txt').css('border', '2px solid red');
                        e.preventDefault();
                }
        });
        $('#comment_btn').click(function(e) {
                $('#mks_txt').css('border', '2px solid black');
                $('#cl_txt').css('border', '2px solid black');

                if ($('#comment_txt').val().length < 2) {
                        $('#comment_txt').css('border', '2px solid red');
                        e.preventDefault();
                }
        });
});
</script>

My (cosmetic) problem is:

When a user enters invalid value into the first text field ("MKS") and clicks the "Add MKS" button, my code will prevent form submission and make the border of the text field solid red. Then the user changes her mind and decides to enter text into another web form and enters invalid data there again. Then I would have 2 red borders already, which would irritate the user.

I'm trying to workaround this problem by setting the other text fields to solid black on a button click - as you can see above. But this doesn't look good, because the original border has been something else before the user started entering anything.

So I wonder, if I could restore that original css('border') value for all text input fields somehow - when a button is clicked (or maybe on blur or some other event, indicating that the user has switched to another web form?)

Thank you for any suggestions! Alex

UPDATE

My browser is Firefox 3.6.12 / WinXP, but I want all browsers work of course :-)

UPDATE 2

The HTML code for the 3 web forms is below and I only have text and links besides that, no further elements at the web page:

<form>
<tr valign="top">
<th>MKS</th><td>
<input name="show_id" type="hidden" value="20110111172527685">
<input name="toggle_mks" id="mks_txt" type="text" size="10" maxsize="10">
<input type="submit" id="mks_btn" value="Add MKS" class="toggle">
</td></tr>
</form>

<form>
<tr bgcolor="#EEEEEE" valign="top">
<th>CL</th><td>
<input name="show_id" type="hidden" value="20110111172527685">
<input name="toggle_cl" id="cl_txt" type="text" size="10" maxsize="10">
<input type="submit" id="cl_btn" value="Add CL" class="toggle">
</td></tr>
</form>

<form>
<tr valign="top">
<th>Comments</th><td>
<input name="show_id" type="hidden" value="20110111172527685">
<textarea name="comment" id="comment_txt" rows="4" cols="60" maxsize="320">
</textarea>
<input type="submit" id="comment_btn" value="Add comment" class="toggle">
</td></tr>
</form>

4 Answers 4

2

instead of

$('#mks_txt').css(

create two css-classes in the stylesheet, one for normal state and one for error state. apply the normal state class in the HTML and set the error state class via jQuery.

.className {
   border: 2px solid red;
}

use

 $('#mks_txt').addClass("className");

to add a class and use

 $('#mks_txt').removeClass("className");

to remove it and restore the element to its previous state. This way you can decorate your alements with a lot more "features" like background-color or font-style as well.

Update: you can do something like:

    /** css: **/
    input {
      border:solid 1px;
    }
    .error {
       border-color:#f00;
    }     


    /** script: **/

            var resetForm = function () {
          $('#cl_txt, #comment_txt, #mks_txt').removeClass('error');
    }
    var renderError = function (elm, isValid) {
          if(!isValid){
             elm.addClass('error');
          }
    }
    var validate = function (value, reg){
        return value.match(reg);
    }

    $('#mks_btn').click(function(e) {
            resetForm();
            var elm = $('#mks_txt');
            renderError(elm, validate(elm.val(), 
                                         /^(CL\s*)?[0-9]{6,}$/i))
            e.preventDefault();
    });
    $('#cl_btn').click(function(e) {
            resetForm();
            var elm = $('#cl_txt');
            renderError(elm, validate(elm.val(), 
                            /^(MKS\s*)?[0-9]{6,}$/i))
            e.preventDefault();
    });
    $('#comment_btn').click(function(e) {

            resetForm();
            var elm = $('#comment_txt');
            renderError(elm, validate(elm.val(),
                             elm.val().length < 2))
            e.preventDefault();
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks - this is good suggestion, any ideas please on how to automate the removeClass() call on some event (blur?) And also: is it still ok to call $('#mks_txt').removeClass("className"); if that field didn't had that class added?
I added a sample, and yes you can remove classes that do not exist on elements, jQuery will accept that.
You call e.preventDefault() on every button click :-) but it's ok, I get the idea, thanks. Do you think it is ok to call match() on empty input fields too? jQuery seems to accept that as well
2

I would would save the element's class value into the the element's .data() collection as soon as the page is loaded.

$('input')each(function(i) { 
   $(this).data('original_class', $(this).attr('class'))
});

Then use .data('original_class') to retrieve it.

UPDATE: I would leave individual css properties alone as that can get messy and now youre inlining css styles inside your JavaScript. I would define an .error class in the stylesheets and just toggle that on or off.

Comments

1

Create css rules in your style sheet for an errors class (something like .formerror), then use:

$('#IDOFBOX').toggleClass('formerror');

Then CSS might be

.formerror{border: 2px solid red;}

Comments

0

Consider setting CSS classes instead of raw CSS in your jQuery - it's easier to maintain (colors and cosmetics goes in the CSS) and let's you work on a higher abstraction.

For instance, you set a "validationError" CSS class to the desired HTML element if it fails validation (style it with a red border in the external CSS stylesheet) and simply remove it again when you want to return to the default.

http://api.jquery.com/addClass/

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.