1

Am trying to put together a form validation script, and i hit a snag when i wanted to have callback functions in my validation rules. The validation rules are defined in the html using data attributes here the html

<div class="clearfix">
                    <input type="text" name="first_name" placeholder="First Name" id="_fname" data-required='yes' />
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>
               <div class="clearfix">
                    <input type="text" name="last_name" placeholder="Last Name" id="_lname" data-required='yes' />
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>
               <div class="clearfix">
                    <input type="text" name="email" 
                         placeholder="Email Address" id="_email"
                         data-required='yes' data-has-callback="yes"
                         data-callback="email_check" 
                     />
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>

               <div class="clearfix">
                    <input type="text" name="username" 
                        placeholder="Username" id="_username" 
                        data-required='yes' data-has-callback="yes"
                        data-callback="username_check" 
                    />
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>
               <div class="clearfix">
                    <input type="password" name="password" placeholder="Password" id="_password" data-required='yes'/>
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>
               <div class="clearfix">
                    <input type="password" name="confpass" placeholder="Confirm Password" id="_confpass" data-required='yes' />
                    <span class="form-validation-status"></span>
                    <div class="form-error-msg"></div>
               </div>
               <div class="clearfix">
                    <input type="submit" value="Sign Up" class="btn btn-large btn-primary" id="signup-btn" />
               </div>

I've been able to deal with the required rule, but i cant seem to figure what to do for the callbacks, this the javascript

var required_fields = $("input[data-required='yes']");
        var has_callbac =$("input[data-has-callback='yes']");

        /* VALIDATE REQUIRED FIELDS */
        $.each(required_fields,function(index,item){
            var field = $(item);
            var status = field.next();
            var field_name = field.attr("placeholder");
            var error_msg = "The "+field_name+" cannot be empty";
            var form_error = field.siblings('span.form-validation-status').next();
            field.blur(function() {
                var _field_val = ($(this).val());
                form_error.html('');
                status.removeClass('error-status');
                if(_field_val == ""){
                    validation_errors++;
                    status.addClass('error-status');
                    form_error.html(error_msg);
                }else {
                    status.addClass('ok-status');
                    validation_errors= validation_errors + 1 - 2;
                }
            });
        });

        /* VALIDATE FIELDS WITH CALLBACKS */
        $.each(has_callbac,function(index,item) {
            var field = $(item);
            var status = field.next();
            var form_error = field.siblings('span.form-validation-status').next();
            var callback = field.attr("data-callback");
            var callback_func = callback+"()";
            var test = typeof callback_func;
                    //i got confused at this point
            console.log(test);
        });

Please help me out.

2 Answers 2

2

If these callback functions are global, you can simply do:

var callback = field.attr("data-callback");
window[callback]();

Or, if your callback would like to have the field in question set as the this value, then you'd do:

var callback = field.attr("data-callback");
window[callback].call(field); //and of course tack on any other parameters you have

If you've defined these callbacks as properties of some other object, then you'd do the same thing:

var callbackHolder = {
    callback1: function() { },
    callback2: function() { }
};

var callback = field.attr("data-callback");
callbackHolder[callback]();
Sign up to request clarification or add additional context in comments.

2 Comments

will i be able to attach these callbacks to event handler like "blur" which i used in the first validation function for required fields
@MrFoh - assuming these callback functions are global, then yes, you can attach them wherever you want
1

you have this:

var callback = field.attr('data-callback');

Extend it to this:

// check if the value is a function in the global scope

if('function' == typeof(window[callback])) {
 callback();
}

If the functions are not in the global scope, you may need to modify that logic.

EDIT:

If you are working in the local scope, you may benefit from adding a generic validation function such as:

(function($){
 $.fn.form_validation=function(){
   var rules = {
     callback_one: function(fieldvalue) {
       var response = {
         'code':'failed',
         'reason':'Missing or incomplete'
       };
       //some validation here
       return response;
     }, ...
   }
   var rule = '', args = [];

   if(arguments.length > 0) {
      if('object' === typeof(arguments[0])) {
         args = arguments;
      } else if('undefined' !== typeof(rules[arguments[0]])) {
         args = Array.prototype.slice.call(arguments);
         args.shift();
         rule = arguments[0];
      }
   }
   rules[ rule ].apply( this, args );
 }
}($));

Then you could call something like:

var result = $.form_validation(callback,data);

within your $.each()

NOTE: untested - just a starting point to separate our your code into controllable modules rather than bring it all inline in case you need to reuse your validation or edit your code inline.

1 Comment

the functions are to be in the local scope of the module

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.