[Solved] Validate inputs with jQuery [closed]


  • The first point to keep in mind that the code must be object oriented as possible.
  • Should be understood that must be validated both the client side and the server side.
  • You have to know that in addition to receiving the data with expected values​​, still may not be safe for use in queries to the database

So after these points, proceed to give a clear example.

index.html

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    <head>
      <meta charser="utf-8" />
      <title>Form Validation</title>
      <script type="text/javascript" src="https://stackoverflow.com/questions/15377653/./js/jquery.js"></script>
    </head>

    <body>
      <div class="form-container">
        <form action="form_proccess.php" method="post" class="must-validate">
          <p>Nick<input type="text" name="nick" class="input-validate"/></p>
          <p>Password<input type="password" name="password" class="input-validate"/></p>
          <p>Email<input type="text" name="email" class="input-validate"/></p>
          <p>Name<input type="text" name="name" class="input-validate"/></p>
          <p>Country<input type="text" name="country" class="input-validate"/></p>
          <p>Birthday<input type="text" name="birthday" class="input-validate"/></p>
          <input type="submit" value="Send!" />
        </form>
      </div>
      <div id="form-errors">
        <ul></ul>
      </div>



    <script type="text/javascript">
      ;(function () {

        var Rules = {
          "nick"     : /^[0-9a-zA-Z_]{5,20}$/
        , "password" : /^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/
        , "email"    : /^[_a-z0-9.-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/
        , "name"     : /^[a-zA-Z -]+$/
        , "birthday" : /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/
        , "country"  : /^[a-zA-Z]+$/
      }

      , Messages = { 
          "nick"     : "The nick can contain numbers, letters and underscores, between 5 and 20 characters."
        , "password" : "The password should contain uppercase and numbers at least 8 characters."
        , "email"    : "The email must be valid."
        , "name"     : "The name can contains only letters and spaces"
        , "birthday" : "The date must be in the format YYYY/MM/DD."
        , "country"  : "The country must contain only letters."
      }

      ;

      $(document).ready( function () {

        $('.must-validate').submit( function ( pressed ) {

            var form   = $(this).get(0)
              , inputs = $(form).find('.input-validate')
              , passed = true
              , errors = [ ]
              , input
              , html=""
              ;

            $.each( inputs, function( key, value ) {
                input = inputs [ key ];
                if(!Rules [ input.name ].test( input.value ) ) {
                    passed = false;
                    errors.push( Messages[ input.name ] );
                }
            });

            if ( errors.length ) {
                $.each( errors, function ( errorKey, errorValue ) {
                    html+= '<li>';
                    html+= errorValue;
                    html+= '</li>';
                });
                $('#form-errors ul').append(html);
            }

            return passed;

        });
      });

    })();
  </script>
</body>
</html>
  • Basic HTML document, in which we validate the form with javascript [in this example I used jQuery, but works perfectly without it].
  • when you submit the form in question, the browser runs an event in which we proceed with the validation.
  • A variable contains regular expressions and messages from them. Can add as many as you like.
  • We compare the values ​​of the inputs, (must have the class .validate input); sure that you can change and modify it.
  • finally, if all goes well, will send the form data to the server. By contrary, if there is an error, then show the user the details so he can correct them. You can remove the error messages if you want, but this would not be very accessible to the user, and this should be as predictive as possible.

Validator.php

/**
 * All the regular expressions to be used
 */
private static $_rules = array(
        "nick"      => '/^[0-9a-zA-Z_]{5,20}$/'
      , "password"  => '/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/'
      , "birthday" => '/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/'
      , "email"     => '/^[_a-z0-9.-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'
      , "name"      => '/^[a-zA-Z -]+$/'
      , "country"   => '/^[a-zA-Z]+$/'
);

/**
 * The flag contains the names of all the input that must be validated; 
 * Note that the flags elements must match with some of the rules elements.
 */

private $_flags;

  /**
   * Set the flags
   */

public function __construct ( Array $flags ) {
    $this->_flags = $flags;
}

/**
 * Set the data to be validated
 */

public function validate ( Array $data ) {

    $passed = true;

    if ( count ( $data ) == 0 ) {
        $passed = false;
    }
    else {

        foreach ( $this->_flags as $key ) {

            if ( ! in_array ( $key, array_keys ( $data ) ) )
                $passed = false;

            if ( $data [ $key ] == null ) 
                $passed = false;

            if ( ! preg_match( self::$_rules [ $key ], $data [ $key ] ) ) 
                $passed = false;
        }
    }

    return (bool) $passed;
  }
}
  • In this class, we have all the regular expressions in a static variable.
  • The constructor has a parameter that lets you specify which items should be considered to be validated, making clear the regular expressions that we use.
  • Finally, the function validate() takes as a parameter an array() of all the values ​​we want to analyze.

form_proccess.php

<?php
require_once 'Validator.php';

$validator = new Validation( array (
      "nick"
    , "password"
    , "email"
    , "name"
    , "country"
    , "birthday"
  )
);

$passed = $validator->validate( $_POST );

if ( $passed ) {
    /**
     * The data received was validated :)
     */
}
else {
    /**
     * Some error ocurred!
     */
}

I hope this has helped.-

solved Validate inputs with jQuery [closed]