473,406 Members | 2,390 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Learning JS the hard way: need help modifying a validate function.

SIMPLIFIED QUESTION: How can I get the error message to display before the black box? (code here)

I have tried to avoid the need to learn javascript, mainly because I'm aging and already have enough web "programming languages" filling up the cranium :) as it is, but have come to the point where I must learn a bit ... at least.

Since I only want to use it to modify an existing jQuery function, that validates form fields using the Bootstrap2 css framework, I haven't extensively read up on the language. I am well acquainted with programming languages in general, and do pick up on things rather quickly, but just don't have the time to acquaint myself with another language that I will only be using once or twice in the next few months, if that. So, please help guide me along with solving the problem below.

The code started out as a jQuery live form validation function created by GeekTantra, then modified for use with Bootstrap2 by ddarren, and worked rather well for basic multi-field forms. However, as things usually go, I wanted to use it in a way it wasn't designed for, and its functionality "broke."

I want to use it to validate a single-field "subscriber" type form that asks only for a valid email address, which has no actual label attached to it, and placed the error (failed validation) message before the field (and a prepended icon) instead of after it.

Originally I just changed the jQuery ".after" function to a ".before" one, and everything seemed to work until the user made multiple attempts resulting in invalid field data, this would place multiple instances of the error message - needless to say it got quite messy :D.

Anyway, after stripping what I believed to be unnecessary code (stuff related to multiple field testing) and having it only validate after the user pressed submit, managed to get it working ... partially. My current problems are the placing of the error message before the prepended field "add-on", plus adding and removing the "error" class to the appropriate "control-group" div.

In addition to the code below, I have setup a jsFiddle bin for testing purposes. All help would be appreciated, and I will definitely take the time to respond to all posts. Thanks.

HTML:

Expand|Select|Wrap|Line Numbers
  1. <form id="Form1" class="form-inline" method="POST" action="">
  2.     <fieldset>
  3.         <div class="control-group">
  4.             <div class="controls pull-right">
  5.                 <div class="input-prepend input-append">
  6.                     <span class="add-on"><i class="icon-envelope icon-large"></i></span>
  7.                     <input class="span3" id="email" name="email" type="email" required placeholder="Enter your email address">
  8.                     <button class="btn btn-large btn-inverse" type="submit">Subscribe!</button>
  9.                 </div>
  10.             </div>
  11.         </div>
  12.     </fieldset>
  13. </form>​
  14.  
CSS just to let me know that the "error" class has been added to the proper div (that has a "control-group" class):

Expand|Select|Wrap|Line Numbers
  1. .error { color: red;}​
  2.  
The stripped down JS validate function, so far:

Expand|Select|Wrap|Line Numbers
  1. (function(jQuery) {
  2.     var ValidationErrors = new Array();
  3.     jQuery.fn.validate = function(options) {
  4.         options = jQuery.extend({
  5.             expression: "return true;",
  6.             message: "",
  7.             error_message_class: "help-inline",
  8.             error_container_class: "control-group"
  9.         }, options);
  10.         var SelfID = jQuery(this).attr("id");
  11.         var FormID = jQuery(this).closest('form').attr("id");
  12.         if (!((typeof(ValidationErrors[FormID]) == 'object') && (ValidationErrors[FormID] instanceof Array))) {
  13.             ValidationErrors[FormID] = new Array();
  14.         }
  15.         jQuery(this).parents("form").submit(function() {
  16.  
  17.             if (validate_field('#' + SelfID)) {
  18.                 return true;
  19.             }
  20.             else return false;
  21.         });
  22.  
  23.         function validate_field(id) {
  24.             var self = jQuery(id).attr("id");
  25.             var expression = 'function Validate(){' + options['expression'].replace(/VAL/g, 'jQuery(\'#' + self + '\').val()') + '} Validate()';
  26.             var validation_state = eval(expression);
  27.             if (!validation_state) {
  28.                 if (jQuery(id).prev('.' + options['error_message_class']).length == 0) {
  29.                     jQuery(id).before('<span class="' + options['error_message_class'] + '">' + options['message'] + '</span>');
  30.                     jQuery(id).closest("div ." + options['error_container_class']).addClass("error")
  31.                 }
  32.                 if (ValidationErrors[FormID].join("|").search(id) == -1) ValidationErrors[FormID].push(id);
  33.                 return false;
  34.             }
  35.             else {
  36.                 for (var i = 0; i < ValidationErrors[FormID].length; i++) {
  37.                     if (ValidationErrors[FormID][i] == id) ValidationErrors[FormID].splice(i, 1);
  38.                 }
  39.                 return true;
  40.             }
  41.         }
  42.     };
  43.     jQuery.fn.validated = function(callback) {
  44.         jQuery(this).each(function() {
  45.             if (this.tagName == "form") {
  46.                 jQuery(this).submit(function() {
  47.                     if (ValidationErrors[jQuery(this).attr("id")].length == 0) callback();
  48.                     return false;
  49.                 });
  50.             }
  51.         });
  52.     };
  53. })(jQuery);
  54.  
  55.  
  56. $(function() {
  57.     $("#email").validate({
  58.         expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/) && VAL) return true; else return false;",
  59.         message: "Error! (proper email required)"
  60.     });
  61. });​
  62.  
As you can see, it uses the Bootstrap2 "error" and "help-inline" classes to show the error message.
May 3 '12 #1
1 1846
If you don't want to waste your time reading the entire post, just read the "SIMPLIFIED QUESTION" and look at the linked site.

Thanks
May 4 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is...
3
by: Dave | last post by:
Hi, This way to start a function works with IE; why doesn't it work with NS (7). <input type="button" id="test"> <script> function test.onclick() { .... }
4
by: KathyB | last post by:
Hi. I have an hmtl page with a function to see if there are any input text boxes. If so, that means a user did not complete them (once entered, my xsl stylesheet makes them text instead of text...
4
by: Frank Rocco | last post by:
Hello, What is the best way to validate a textbox to see if it contains a valid date or a valid time or both? Thanks Frank
7
by: lovecreatesbea... | last post by:
K&R 2, sec. 5.11 says that no need to precede function and array names with address-of operators &, why?
10
by: Matthew Wilson | last post by:
Lately, I've been writing functions like this: def f(a, b): assert a in assert b in The point is that I'm checking the type and the values of the parameters.
6
by: poison.summer | last post by:
int type(int a) { return 0; } thanks a lot!
2
by: yong321 | last post by:
My question is not about Javascript programming. I'd like to use a browser, either IE or Firefox or whatever, that allows me to disable a specific Javascript function but not disable Javascript...
12
by: aaragon | last post by:
I have this scenario: several arrays for which I have their fixed values at compilation time. Now, at runtime I need to access a specific array depending on an integer but I want to avoid if and...
13
by: BobLewiston | last post by:
Can anybody tell me how to change WinForm controls' text color programatically? I have no problem finding the fields to assign colors to, but the compiler doesn't recognize any color I mention,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.