SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 34 of 34

Thread: Would like comments and views on this form validation :)

  1. #26
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i'm working on the same exact thing, minus Postgres. my goal is to generate the code-behind/html from an XML map of the data (form <--> validation <--> storage).
    I was thinking along the same lines as you though I've yet to find the time to really think about it, so would be interested in seeing how far others have got

  2. #27
    SitePoint Enthusiast
    Join Date
    Apr 2004
    Location
    Land of the Dead
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice threads, man.

    I've attached the code.

    [EDIT]

    A sample MySQL database...

    Code:
    # Database : `app`
    
    CREATE TABLE `groups` (
      `groups_id` int(11) NOT NULL default '0',
      `name` varchar(50) NOT NULL default '',
      PRIMARY KEY  (`groups_id`),
      UNIQUE KEY `name` (`name`)
    ) TYPE=InnoDB;
    
    CREATE TABLE `user_groups` (
      `users_id` int(11) NOT NULL default '0',
      `groups_id` int(11) NOT NULL default '0',
      PRIMARY KEY  (`users_id`,`groups_id`),
    ) TYPE=InnoDB;
    
    CREATE TABLE `users` (
      `users_id` int(11) NOT NULL default '0',
      `name` varchar(50) NOT NULL default '',
      `pass` varchar(32) NOT NULL default '',
      PRIMARY KEY  (`users_id`),
      UNIQUE KEY `name` (`name`)
    ) TYPE=InnoDB;
    [EDIT 2]

    Removed a bunch of bugs, added ValidateButton and ResetButton classes.
    Attached Files
    Last edited by averagejoeguy; Jun 17, 2004 at 14:24.
    Learn how to astral project -- http://mysticweb.org

  3. #28
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    From

    http://www.sitepointforums.com/showt...threadid=77563

    Post #2 by Vincent

    PHP Code:
    ...
    function 
    AddressForm() 
        { 
            
    $this->Form(); 
            
    $this->addField('name'     'text'  false); 
            
    $this->addField('address'  'text'  false); 
            
    $this->addField('telephone''number'true); 
            
    $this->addField('email'    'email' false); 
        } 
    ... 
    In the above example, any given number of form elements are added, though I'm thinking that, instead of adding form elements, how about adding class(es) ?

    Each class would handle a given type of data, ie Email, Web Url, Phone No., etc ? If each class was a child class of a base validator class, would that method work

  4. #29
    SitePoint Evangelist
    Join Date
    Jun 2003
    Location
    Melbourne, Australia
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OT:

    Quote Originally Posted by mattjacob
    Spelling Police alert
    Give it up, Matt. Excuse my crudeness, but you're pissing into the wind trying to get computer programmers to spell properly. It's something of a paradox that the same people strive to keep their code pristine because their compilers and interpreters won't tolerate syntax errors.

    Besides, native English speakers are the worst speakers of English. Trust me on this one. I live in Australia where 99% of the population is functionally illiterate.

  5. #30
    SitePoint Zealot
    Join Date
    Dec 2003
    Location
    with my kids
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Widow Maker
    In the above example, any given number of form elements are added, though I'm thinking that, instead of adding form elements, how about adding class(es) ?

    Each class would handle a given type of data, ie Email, Web Url, Phone No., etc ? If each class was a child class of a base validator class, would that method work
    umm, that's exactly what the code does:
    The above implementation of class Form more or less implies an implementation of a (base)class Field:
    PHP Code:

    class Field
    {
        var 
    $name;
        var 
    $nullAllowed;
        var 
    $value;
        var 
    $isset;
        
        function 
    Field($name$nullAllowed)
        {
            
    $this->name        $name;
            
    $this->nullAllowed $nullAllowed;
            
    $this->value       '';
            
    $this->isset       false;
        }
        
        function 
    setValue($value)
        {
            
    $this->value $value;
            
    $this->isset true;
        }
        
        function 
    isValid()
        {
            if (!
    $this->hasValue() || $this->isEmpty())
            {
                return 
    $this->nullAllowed;
            }
            return 
    true;
        }
        
        function 
    isEmpty()
        {
            return empty(
    $this->value);
        }
        
        function 
    hasValue()
        {
            return 
    $this->isset;
        }
        
        function 
    getValue()
        {
            return 
    $this->value;
        }
        
        function 
    isNullAllowed()
        {
            return 
    $this->nullAllowed;
        }

    This simple class can serve as a base class for other fields. An email field for example could be implemented like this:
    PHP:
    PHP Code:
    class EmailField extends Field
    {
        function 
    isValid()
        {
            if (
    parent::isValid())
            {
                if (!
    $this->isEmpty())
                {
                    return 
    $this->checkEmail();
                }
                return 
    true;
            }
            return 
    false;
        }
        
        function 
    checkEmail()
        {
            
    $address $this->getValue();
            
    // Run some regular expression on the email address and return true/false
            
    return true;
        }
        

    Now, the problem that remains is creating the right kind of Field-objects for the right fields. As you probably already guessed, this can be done with some sort of Factory:
    PHP Code:
    class FieldFactory
    {
        function &
    createField($name$type$nullAllowed)
        {
            switch (
    $name)
            {
                case 
    'text'  $class 'Field'; break;
                case 
    'number'$class 'NumberField'; break;
                case 
    'email' $class 'EmailField'; break;
                default      : 
    $class 'Field'; break;
            }
            include_once(
    $class '.php');
            return new 
    $class($name$nullAllowed);
        }


  6. #31
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Could do

  7. #32
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay, I was never too happy with the original methods I used, so I've made some changes ?

    But now I'm finding it really difficult on how to allow for required fields or not. Do I check for these before or after I validate a field for example ?

    Just can't see a good way of doing it I suppose, and need some help

    contact.php (configuration)
    PHP Code:
    # contact form
        
        
    $form['title'] = &new FormSelectField$_POST['Title'], array(
                    
    'ALIAS'            =>        'Title',
                    
    'ERROR'            =>        array(
                        
    'Please be sure to select an option.' ),
                    
    'PATTERN'        =>        '/^[1-9]$/',
                    
    'REQUIRED'        =>        ) );
                
                
    $form['forename'] = &new FormTextBoxField$_POST['Forename'], array(
                    
    'ALIAS'            =>        'Forename',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[a-zA-Z]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'MAXIMUM'        =>        32,
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['surname'] = &new FormTextBoxField$_POST['Surname'], array(
                    
    'ALIAS'            =>        'Surname',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[a-zA-Z]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'MAXIMUM'        =>        32,
                    
    'REQUIRED'        =>        ) );
                
                
    $form['company'] = &new FormTextBoxField$_POST['Company'], array(
                    
    'ALIAS'            =>        'Company',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[a-zA-Z ]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'MAXIMUM'        =>        64,
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['position'] = &new FormTextBoxField$_POST['Position'], array(
                    
    'ALIAS'            =>        'Position',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[a-zA-Z]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'MAXIMUM'        =>        32,
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['email'] = &new FormTextBoxField$_POST['Email'], array(
                    
    'ALIAS'            =>        'Email',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+([0-9A-Z]){2,4}$/i',
                    
    'MAXIMUM'        =>        64,
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['telcode'] = &new FormTextBoxField$_POST['TelCode'], array(
                    
    'ALIAS'            =>        'Tel Code',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.' ),
                    
    'PATTERN'        =>        '/^[0-9]+$/',
                    
    'MINIMUM'        =>        5,
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['telnumb'] = &new FormTextBoxField$_POST['TelNumber'], array(
                    
    'ALIAS'            =>        'Tel Number',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.',
                        
    'This field is too long.' ),
                    
    'PATTERN'        =>        '/^[0-9]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'MAXIMUM'        =>        12,
                    
    'REQUIRED'        =>        ) );
                
                
    $form['department'] = &new FormSelectField$_POST['Department'], array(
                    
    'ALIAS'            =>        'Department',
                    
    'ERROR'            =>        array(
                        
    'Please be sure to select an option.' ),
                    
    'PATTERN'        =>        '/^[1-9]$/',
                    
    'REQUIRED'        =>        ) );
                    
                
    $form['message'] = &new FormTextBoxField$_POST['Message'], array(
                    
    'ALIAS'            =>        'Message',
                    
    'ERROR'            =>        array(
                        
    'This field has illegal characters.',
                        
    'This field is too short.' ),
                    
    'PATTERN'        =>        '/^[a-zA-Z0-9]+$/',
                    
    'MINIMUM'        =>        6,
                    
    'REQUIRED'        =>        ) ); 
    The validator(s)
    PHP Code:
    class FormValidator {
            var 
    $msg;
            
            function 
    FormValidator() {
                
    $this -> msg = array();
                
    #
                
    $this -> Process();
            }
            
            function 
    Process() {
            } 
    # abstract
            
            
    function SetError$msg ) {
                
    $this -> msg[] = $msg;
            }
            
            function 
    GetError() {
                return 
    array_pop$this -> msg );
            }
        }
        
        class 
    FormTextBoxField extends FormValidator {
            var 
    $rule;
            var 
    $field;
            var 
    $error;
            
            function 
    FormTextBoxField$field$rule ) {
                
    $this -> rule $rule;
                
    $this -> field $field;
                
    #
                
    FormValidator::FormValidator();
            }
            
            function 
    IsError() {
                return ( 
    $this -> error == (bool) true )? 1:0;
            }
            
            function 
    Process() {
                
    $this -> error false;
                
                if( !
    preg_match$this -> rule['PATTERN'], $this -> field ) ) {
                    
    $this -> error true;
                    
    $this -> SetError$this -> rule['ALIAS'].' - '.$this -> rule['ERROR'][0] );
                }
                if( isset( 
    $this -> rule['MINIMUM'] ) ) {
                    if( 
    strlen$this -> field ) < $this -> rule['MINIMUM'] ) {
                        
    $this -> error true;
                        
    $this -> SetError$this -> rule['ALIAS'].' - '.$this -> rule['ERROR'][1] );
                    }
                }
                if( isset( 
    $this -> rule['MAXIMUM'] ) ) {
                    if( 
    strlen$this -> field ) > $this -> rule['MAXIMUM'] ) {
                        
    $this -> error true;
                        
    $this -> SetError$this -> rule['ALIAS'].' - '.$this -> rule['ERROR'][2] );
                    }
                }
            }
        }
        
        class 
    FormSelectField extends FormValidator {
            var 
    $rule;
            var 
    $field;
            var 
    $error;
            
            function 
    FormSelectField$field$rule ) {
                
    $this -> rule $rule;
                
    $this -> field $field;
                
    #
                
    FormValidator::FormValidator();
            }
            
            function 
    IsError() {
                return ( 
    $this -> error == (bool) true )? 1:0;
            }
            
            function 
    Process() {
                
    $this -> error false;
                
                if( !
    preg_match$this -> rule['PATTERN'], $this -> field ) ) {
                    
    $this -> error true;
                    
    $this -> SetError$this -> rule['ALIAS'].' - '.$this -> rule['ERROR'][0] );
                }
            }
        } 
    Example of use
    PHP Code:
    ...
    $form = array();
    @require_once( 
    'contact.php' );
    ... 
    Ideally, the check for a field being required or not should be in the base class, though what is really bugging me, is that if a field is not required, it can pass (validated) as empty, though not if it isn't yes ?

    If a field isn't required, and isn't empty, it will then need to be validated anyways.

    Has anyone any ideas how to solve this, as I'm going round in circles with this

    Thanks.

  8. #33
    SitePoint Addict been's Avatar
    Join Date
    May 2002
    Location
    Gent, Belgium
    Posts
    284
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Widow Maker
    But now I'm finding it really difficult on how to allow for required fields or not. Do I check for these before or after I validate a field for example ?
    I'd say before, how will you otherwise be able to know to do the validation

    The reason that you're finding it difficult to implement this, is probably because you have externalized the fieldname from the rule into the validator. Therefor, you're 'Required rule' will be more likely an isset() or array_key_exists() call in the validator...

    Paths to possible solutions:
    Split the system up into seperate validation rules and a validator (which holds a collection of validation rules), then, as you add each rule to the validator, specify if it is a required field or not, then do the isset()/array_key_exists() call in the validator before passing the data on to the validation rule.
    This has the disadvantage that handling a validation error is more cumbersome: the validator, as well as a validation rule can raise errors, it is not centralized...

    Another way may be to put the field name into the validation rule, and pass the entire dataset to all the rules in a kind of 'fall-through' system, where each rule will then know which data to validate
    This raises another issue: rules will probably extend from a base rule, which has the field name as a property, implying that the validation system is mainly geared towards tabular (record based) data.
    This should be easily overcome though, by implementing a seperate 'FieldRule', for example as a Decorator that takes a rule upon construction.

    Also see the excellent comments Selkirk posted in this thread

    PS: are you simpletesting already?
    Per
    Everything
    works on a PowerPoint slide

  9. #34
    Non-Member
    Join Date
    Jan 2004
    Location
    Planet Earth
    Posts
    1,764
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Been looking at a number of solutions though nothing with any success

    Will be bookmarking the link you've posted so I can read it later though.

    Suppose I will need to look at the options, and choose which one is more suitable to me. Thanks again for your comments

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
  •