SitePoint Sponsor

User Tag List

Results 1 to 8 of 8

Hybrid View

  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Jquery form validation first step.

    Hi.
    I'm taking my first steps with Jquery.
    To practice with it I tried to develope this simple
    validator system:
    PHP Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <
    html>
    <
    head>
    <
    title>Test</title>
    <
    meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <
    script type="text/javascript" src="jquery/jquery-1.2.2.js"></script>
    <script type="text/javascript">
    function isEmpty(val) {
       return !/\S/.test(val);

    function isValidEmail(str) {
        // http://www.devpro.it/php4_id_2.html
        return Boolean(str.match(/^([a-z0-9]+[\._\-]?){1,3}([a-z0-9])*\@([a-z0-9]+[\.\-]?){1,3}([a-z0-9])*\.[a-z]{2,6}$/i));
    };
    function isEmptyV(id,errMsg){
        this.el= $(id);
        this.isValid= function(){
            var isValid= true;
            if(isEmpty($(id).val())){
                this.error= errMsg;
                isValid= false;
            }
            return isValid;
        }
    };
    function isValidEmailV(id,errMsg){
        this.el= $(id);
        this.isValid= function(){
            var isValid= true;
            if(!isValidEmail($(id).val())){
                this.error= errMsg;
                isValid= false;
            }
            return isValid;
        }
    };
    function Validator() {
         var validators= [];
        this.errors= [];
        this.values= {};
        this.add= function(objV){
            validators.push(objV);
        }
        this.isValid= function(){
            var isValidFlag= true;
            for(var i=0, len= validators.length;i< len;i++){
                if(!validators[i].isValid()){
                    this.errors.push({error:validators[i].error,el:validators[i].el});
                    isValidFlag= false;
                }
                else{
                    this.values[$(validators[i].el).attr('id')]=$(validators[i].el).val();
                }
            }
            return isValidFlag;
        }
    }
    function checkForm(){
        var errMsgName= 'Invalid name';
        var errMsgSurname= 'Invalid surname';
        var errMsgEmail= 'Invalid email';
        var validator = new Validator();
        validator.add(new isEmptyV('#c-name',errMsgName));
        validator.add(new isEmptyV('#c-surname',errMsgSurname));
        validator.add(new isEmptyV('#c-email',errMsgEmail));
        if(!validator.isValid()){
            alert(validator.errors[0].error);
            // do something ie set input border style
            $(validator.errors[0].el).css({ border: "1px solid #EE0000"});
                return false;
            }    
            alert(validator.values['c-email']);
            //do something ie send  validator.values with Json
            
    }
    $(document).ready( function () {
        $('#frm').submit(
            function(){
                return checkForm();
            }
        );
    });
    </script>
    </head>
    <body>
    <form action="" method="post" id="frm">
    <p><input type="text" name="c_name"  value="" maxlength="50" tabindex="1" id="c-name"  /></p>
    <p><input type="text" name="c_surname"  value="" maxlength="50" tabindex="2" id="c-surname"  /></p>
    <p><input type="text" name="c_email"  value="" maxlength="50" tabindex="4" id="c-email"  /></p>
    <p><input type="submit" name="c_send" value="Send &raquo;" tabindex="5" id="news-submit"  /></p>
    </form>
    </body>
    </html> 
    I realize it's a mix-up of Jquery and 'old way'
    could you help me to realize a better script ?

    I didn't find anything about sending json data
    with Jquery is there a way without using the standard
    json library ?

    Bye.

  2. #2
    SitePoint Wizard chris_fuel's Avatar
    Join Date
    May 2006
    Location
    Ventura, CA
    Posts
    2,750
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, out of curiosity where is this form being posted to? The general rule is when it comes to form, Javascript is the last last last possible resort to form posting.

    Also it should only be considered an interface addon to form validation. People can modify javascript on the will and totally bypass any validation system.

    As far as sending JSON data, check the AJAX part of jquery (might want to check prototype too). JSON or Java Script Object Notation, is simply a string formated in the same way you do a javascript object literal in line:

    "{ key: value, key2: value2}"

    Though it has a similar notation, be aware that the JSON receiver will not always be able to handle things javascript objects can like such as methods. Here's a link on JQuery's AJAX implementation:

    http://docs.jquery.com/Ajax

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by chris_fuel View Post
    Well, out of curiosity where is this form being posted to? The general rule is when it comes to form, Javascript is the last last last possible resort to form posting.

    Also it should only be considered an interface addon to form validation. People can modify javascript on the will and totally bypass any validation system.
    As usual the form is also validated server-side the script it's
    only an add-on.
    As far as sending JSON data, check the AJAX part of jquery (might want to check prototype too). JSON or Java Script Object Notation, is simply a string formated in the same way you do a javascript object literal in line:

    "{ key: value, key2: value2}"

    Though it has a similar notation, be aware that the JSON receiver will not always be able to handle things javascript objects can like such as methods. Here's a link on JQuery's AJAX implementation:

    http://docs.jquery.com/Ajax
    Yeah, I know the Json stuff (and server-side I'm using php with
    json_encode/json_decode) but I check all JQuery's AJAX implementation
    and I found only jQuery.getJSON( url, [data], [callback] ) and if
    I don't wrong with it you can only get Json data.
    I need send json data.
    It's quite strange that Jquery don't have a proper way to send
    json data without using the standard json library.




    Thanks for the reply

    Bye.

    PS.

    Do have any idea to get the script better ?
    I don't like it very much ;(

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    So far as sending JSON data, it's a much better idea to serialize the data then send that instead.

    What in particular don't you like about the script? Perhaps we can throw some ideas around.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by pmw57 View Post
    So far as sending JSON data, it's a much better idea to serialize the data then send that instead.
    As far as I know it's the opposite ie Google use Json.

    What in particular don't you like about the script? Perhaps we can throw some ideas around.
    For instance I found out this:

    PHP Code:
    function isValidEmailV(id,errMsg){
        
    this.el= $(id);
        
    this.isValid= function(){
            var 
    isValidtrue;
            if(!
    isValidEmail($(this.el).val())){
                
    this.errorerrMsg;
                
    isValidfalse;
            }
            return 
    isValid;
        }
    }; 
    All in all it's not so bad but I'd like to find a way to
    get rid of this:

    PHP Code:
    validator.add(new isEmptyV('#c-name',errMsgName)); 
        
    validator.add(new isEmptyV('#c-surname',errMsgSurname)); 
        
    validator.add(new isEmptyV('#c-email',errMsgEmail)); 
    using for instance

    PHP Code:
    <input type="text" name="c_name"  value="" maxlength="50" tabindex="1" id="c-name"  class="isEmptyV"/> 
    I've tried but it doesn't work


    Bye.

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    So you're wanting to automagically generate the validation routines instead of having to explicitly specify them in the script. I don't blame you either for I'd want to do the same.

    With the appropriate class name in there you should be able do so with no trouble. It would mean searching through the form elements for appropriate class names, then mapping them to the appropriate function.

    The only issue is how to describe them should an error occur, for which the id name could be used, or perhaps even better the title attribute.

    I suggest that the class names should be intuitively understandable, so that they can be applied without needing to refer to a list of available functions.

    [snip code]

    While working through some form issues with jQuery (the elements array isn't available) I found that jQuery has its own validation plugin.
    Check it out: http://docs.jquery.com/Plugins/Validation
    Last edited by paul_wilkins; Feb 1, 2008 at 22:55.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Man at work
    PHP Code:
    function isEmptyV(id,errMsg){ 
        
    this.el= $(id); 
        
    this.isValid= function(){ 
            var 
    isValidtrue
            if(
    isEmpty(this.el.val())){ 
                
    this.errorerrMsg
                
    isValidfalse
            } 
            return 
    isValid
        } 
    }; 
    function 
    isValidEmailV(id,errMsg){ 
        
    this.el= $(id); 
        
    this.isValid= function(){ 
            var 
    isValidtrue
            if(!
    isValidEmail(this.el.val())){ 
                
    this.errorerrMsg
                
    isValidfalse
            } 
            return 
    isValid
        } 
    }; 
    function 
    Validator() { 
        var 
    validators= []; 
        
    this.errors= []; 
        
    this.values= {}; 
        
    this.add= function(objV){ 
            
    validators.push(objV); 
        } 
        
    this.isValid= function(){ 
            var 
    isValidFlagtrue
            for(var 
    i=0lenvalidators.length;ilen;i++){ 
                if(!
    validators[i].isValid()){ 
                    
    this.errors.push({error:validators[i].error,el:validators[i].el}); 
                    
    isValidFlagfalse
                } 
                else{
                    
    this.values[validators[i].el.attr('id')]= validators[i].el.val(); 
                } 
            } 
            return 
    isValidFlag
        } 

    I get rid of all useless $()
    with this.el= $(id) I've got a reference to $().


    Bye.

  8. #8
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by whisher View Post
    Hi.
    I didn't find anything about sending json data
    with Jquery is there a way without using the standard
    json library ?
    Bye.
    I found it you have to use json.js
    within Jquery
    http://jollytoad.googlepages.com/json.js



    Bye.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •