Saturday, 6 December 2014

Yii 2 Latest Features (Highlights)

yii2 yii 2 php yii 2 yii2 highlights latest features yii2 yii 2 RESTful APIs yii 2 yii2 Adopting Standards and Latest Technologies yii2 yii 2 Solid Foundation Classes yii2 yii 2 Security yii2 yii 2 Database Caching forms yii2 yii 2 Authentication and Authorization Widgets Helpers yii2 yii 2 Internationalization Template Engines Testing Application Templates

Adopting Standards and Latest Technologies

Yii 2.0 adopts PHP namespaces and traits, PSR standards, Composer and Bower. All these make the framework more refreshing and interoperable with other libraries.

Solid Foundation Classes

Like in 1.1, Yii 2.0 supports object properties defined via getters and setters, configurations, events and behaviors. The new implementation is more efficient and expressive. For example, you can write the following code to respond to an event:
$response = new yii\web\Response;
$response->on('beforeSend', function ($event) {
    // respond to the "beforeSend" event here
});
Yii 2.0 implements the dependency injection container and service locator. It makes the applications built with Yii more customizable and testable.

Development Tools

Yii 2.0 comes with several development tools to make the life of developers easier.
The Yii debugger allows you to examine the runtime internals of your application. It can also be used to do performance profiling to find out the performance bottlenecks in your application.
Like 1.1, Yii 2.0 also provides Gii, a code generation tool, that can cut down a large portion of your development time. Gii is very extensible, allowing you to customize or create different code generators. Gii provides both Web and console interfaces to fit for different user preferences.
The API documentation of Yii 1.1 has received a lot of positive feedback. Many people expressed the wish to create a similar documentation for their applications. Yii 2.0 realizes this with a documentation generator. The generator supports Markdown syntax which allows you to write documentation in a more succinct and expressive fashion.

Security

Yii 2.0 helps you to write more secure code. It has built-in support to prevent SQL injections, XSS attacks, CSRF attacks, cookie tampering, etc. Security experts Tom Worster and Anthony Ferrara even helped us review and rewrite some of the security-related code.

Databases

Working with databases has never been easier. Yii 2.0 supports DB migration, database access objects (DAO), query builder and Active Record. Compared with 1.1, Yii 2.0 improves the performance of Active Record and unifies the syntax for querying data via query builder and Active Record. The following code shows how you can query customer data using either query builder or Active Record. As you can see, both approaches use chained method calls which are similar to SQL syntax.
use yii\db\Query;
use app\models\Customer;
 
$customers = (new Query)->from('customer')
    ->where(['status' => Customer::STATUS_ACTIVE])
    ->orderBy('id')
    ->all();
 
$customers = Customer::find()
    ->where(['status' => Customer::STATUS_ACTIVE])
    ->orderBy('id')
    ->asArray();
    ->all();
The following code shows how you can perform relational queries using Active Record:
namespace app\models;
 
use app\models\Order;
use yii\db\ActiveRecord;
 
class Customer extends ActiveRecord
{
    public static function tableName()
    {
        return 'customer';
    }
 
    // defines a one-to-many relation with Order model
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }
}
 
// returns the customer whose id is 100
$customer = Customer::findOne(100);
// returns the orders for the customer
$orders = $customer->orders;
And the following code shows how you can update a Customer record. Behind the scene, parameter binding is used to prevent SQL injection attacks, and only modified columns are saved to DB.
$customer = Customer::findOne(100);
$customer->address = '123 Anderson St';
$customer->save();  // executes SQL: UPDATE `customer` SET `address`='123 Anderson St' WHERE `id`=100
Yii 2.0 supports the widest range of databases. Besides the traditional relational databases, Yii 2.0 adds the support for Cubrid, ElasticSearch, Sphinx. It also supports NoSQL databases, including Redis and MongoDB. More importantly, the same query builder and Active Record APIs can be used for all these databases, which makes it an easy task for you to switch among different databases. And when using Active Record, you can even relate data from different databases (e.g. between MySQL and Redis).
For applications with big databases and high performance requirement, Yii 2.0 also provides built-in support for database replication and read-write splitting.

RESTful APIs

With a few lines of code, Yii 2.0 lets you to quickly build a set of fully functional RESTful APIs that comply to the latest protocols. The following example shows how you can create a RESTful API serving user data.
First, create a controller class app\controllers\UserController and specify app\models\User as the type of model being served:
namespace app\controllers;
 
use yii\rest\ActiveController;
 
class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}
Then, modify the configuration about the urlManager component in your application configuration to serve user data in pretty URLs:
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    ],
]
That's all you need to do! The API you just created supports:
  • GET /users: list all users page by page;
  • HEAD /users: show the overview information of user listing;
  • POST /users: create a new user;
  • GET /users/123: return the details of the user 123;
  • HEAD /users/123: show the overview information of user 123;
  • PATCH /users/123 and PUT /users/123: update the user 123;
  • DELETE /users/123: delete the user 123;
  • OPTIONS /users: show the supported verbs regarding endpoint /users;
  • OPTIONS /users/123: show the supported verbs regarding endpoint /users/123.
You may access your API with the curl command like the following,
$ curl -i -H "Accept:application/json" "http://localhost/users"

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
X-Powered-By: PHP/5.4.20
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self, 
      <http://localhost/users?page=2>; rel=next, 
      <http://localhost/users?page=50>; rel=last
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

[
    {
        "id": 1,
        ...
    },
    {
        "id": 2,
        ...
    },
    ...
]

Caching

Like 1.1, Yii 2.0 supports a whole range of caching options, from server side caching, such as fragment caching, query caching to client side HTTP caching. They are supported on a variety of caching drivers, including APC, Memcache, files, databases, etc.

Forms

In 1.1, you can quickly create HTML forms that support both client side and server side validation. In Yii 2.0, it is even easier working with forms. The following example shows how you can create a login form.
First create a LoginForm model to represent the data being collected. In this class, you will list the rules that should be used to validate the user input. The validation rules will later be used to automatically generate the needed client-side JavaScript validation logic.
use yii\base\Model;
 
class LoginForm extends Model
{
    public $username;
    public $password;
 
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }
 
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     */
    public function validatePassword()
    {
        $user = User::findByUsername($this->username);
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError('password', 'Incorrect username or password.');
        }
    }
}
Then create the view code for the login form:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
 
<?php $form = ActiveForm::begin() ?>
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <?= Html::submitButton('Login') ?>
<? ActiveForm::end() ?>

Authentication and Authorization

Like 1.1, Yii 2.0 provides built-in support for user authentication and authorization. It supports features such as login, logout, cookie-based and token-based authentication, access control filter and role-based access control (RBAC).
Yii 2.0 also provides the ability of the authentication via external credentials providers. It supports OpenID, OAuth1 and OAuth2 protocols.

Widgets

Yii 2.0 comes with a rich set of user interface elements, called widgets, to help you quickly build interactive user interfaces. It has built-in support for Bootstrap widgets and jQuery UI widgets. It also provides commonly used widgets such as pagers, grid view, list view, detail, all of which make Web application development a truly speedy and enjoyable process. For example, with the following lines of code, you can create a fully functional jQuery UI date picker in Russian:
use yii\jui\DatePicker;
 
echo DatePicker::widget([
    'name' => 'date',
    'language' => 'ru',
    'dateFormat' => 'yyyy-MM-dd',
]);

Helpers

Yii 2.0 provides many useful helper classes to simplify some common tasks. For example, the Html helper includes a set of methods to create different HTML tags, and the Url helper lets you more easily creates various URLs, like shown below:
use yii\helpers\Html;
use yii\helpers\Url;
 
// creates a checkbox list of countries
echo Html::checkboxList('country', 'USA', $countries);
 
// generates a URL like "/index?r=site/index&src=ref1#name"
echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);

Internationalization

Yii has strong support for internationalization, as it is being used all over the world. It supports message translation as well as view translation. It also supports locale-based plural forms and data formatting, which complies to the ICU standard. For example,
// message translation with date formatting
echo \Yii::t('app', 'Today is {0, date}', time());
 
// message translation with plural forms
echo \Yii::t('app', 'There {n, plural, =0{are no cats} =1{is one cat} other{are # cats}}!', ['n' => 0]);

Template Engines

Yii 2.0 uses PHP as its default template language. It also supports Twig and Smarty through its template engine extensions. And it is also possible for you to create extensions to support other template engines.

Testing

Yii 2.0 strengthens the testing support by integrating Codeception and Faker. It also comes with a fixture framework which coupled with DB migrations, allows you to manage your fixture data more flexible.

Application Templates

To further cut down your development time, Yii is released with two application templates, each being a fully functional Web application. The basic application template can be used as a starting point for developing small and simple Web sites, such as company portals, personal sites. The advanced application template is more suitable for building large enterprise applications that involve multiple tiers and a big developer team.

Sunday, 9 June 2013

Install Yii framework in Ubuntu, Linux or Windows (php)

  • Setup Yii framework php project How to install php application using yii framework on ubuntu Linux windows simple step to install php yii application How to setup yii framework php
First download Yii framework from the site http://www.yiiframework.com/download/

Just follow the steps.


  • Unzip the zip file of Yii framework in to your local server's root and rename the folder as your wish. Lets consider name folder as 'yii'.
e.g. 
  • If you are installing Yii on Ubuntu or any Linux platform then unzip the zip file of Yii under 'var/www/' directory.
  • If you are installing Yii on Window machine using xampp then unzip the zip file of Yii under 'c:\xmapp\htdocs\' (considering xampp installation directory as 'c:\xampp')

  • For windows user, set path of php.exe environment variable. For that open 'Control Panel\System and Security\System' and click on 'Advanced system settings' then click on 'Environment variables' then under 'System variables' label find 'Path' variable, select it and click on edit button and set path of php.exe at then end after symbol ';'(e.g. If you are using xampp, then path is 'c:\xampp\php\php.exe;').

  • Now go to path where your framework directory is located like.
For Ubuntu or Linux users
Open terminal and type
cd /var/www/yii

For Windows users
Open command prompt and type
C:\>cd xampp\htdocs\yii

  • Now create new folder in your local server's root. Lets consider name folder as 'application_name'.

  • Run command to create application based on yii.
For ubuntu or Linux users:
yiic webapp /var/www/application_name

For windows users
yiic webapp C:\xampp\htdocs\application_name

  • Press enter after doing above things and it will ask for following
Create a Web application under '/var/www/application_name’? [Yes|No] y
or
Create a Web application under ‘E:\xampp\htdocs\application_name’? [Yes|No] y

  • Press Enter and all the necessary files will be created under
/var/www/application_name
or
C:\xampp\htdocs\application_name

  • At last you will get message
Your application has been created successfully.

  • URL to access this application is http://localhost/application_name/


If you have any problem, ask freely...!!!

Sunday, 21 April 2013

How to remove / hide index.php from url in yii framework (PHP)

  • remove index.php from url in yii hide index.php from url in yii php url styling php
Just follow steps:

  • Make sure that the hosting / your pc mod_rewrite module is active. if not actively try to activate in a way, open the httpd.conf file. You can check this in the phpinfo.php to find out.
Find line #LoadModule rewrite_module modules/mod_rewrite.so
and remove just '#'

  • Create file .htaccess under directory protected/ or protected/www/ where app's index.php file is hosted and add following code snippet
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

  • Set main.php in your yii configuration, at component :
'urlManager' => array(
                'urlFormat'=>'path',
                'showScriptName'=>false,
                'caseSensitive'=>false,        
               ),

  • Now just hits the your app Url.

Database connection using JDBC ODBC Driver in JAVA

  • java database connection jdbc odbc how to connect java to database database connectivity simple code for java database connectivity

Code Snippet :


import java.sql.*;

class insertIntoTable

{
 public static void main(String args[]) {
       try {

           //load database driver
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
           
           //connect To database
          Connection c;
          c=DriverManager.getConnection("jdbc:odbc:RS");
          System.out.println("connect To database");  
  
           //create Statement
          Statement s;
          s=c.createStatement();
        
          //create String
         String x;
         x="INSERT into RS Values ('Shiva','Aiwale','Vita',21)";
   
          //execute query
         s.executeUpdate(x);
         System.out.println("Data Successfully Inserted");     
         c.close();
      }

      catch(Exception e) 
{
         System.out.println("Exception ="+e.getMessage());
      } 

  }

}

Saturday, 20 April 2013

Steps To Display Database Content to DataGridView in C#

  • .net asp .net how to use data grid view dynamic data in data grid view how to implement datagridview

1)  Establish connection to database :

SqlConnection conObj =  new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WindowsFormsApplication5\WindowsFormsApplication5\StudentDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

Note : 
  • SqlConnection Class found in "System.Data.SqlClient" Namespace, So that you need to specify ( using System.Data.SqlClient; ) namespace
         
2) Create string based on what data need to Display :

        String selectString="SELECT  * FROM employee";

3) Execute above string :


SqlDataAdapter    dataAdapterObj = new SqlDataAdapter(selectString, conObj);

Note : 
  • SqlDataAdapter constructor execute selectString and store result in dataAdapterObj
  • Require two input selectstring to execute and connection object (conObj)

4)Attach data from dataAdapterObject to DataTable object :

        DataAdapter dtObj=new DataAdapter();
                   dtObj.fill(dataAdapterObj );

5)Finally Attach data from data table (dtObj) to DataGridView using DataSource Property :

        datagridview1.DataSource=dtObj;

I hope you got it... If you have any query then ask me...


SAMPLE :





Saturday, 26 January 2013

Database Normalization and Types of Normalization

  • what is normalization and types of normalization 1NF 2NF 3NF with examples SQL simple definition of normalization

Normalization is the techinque of designing the database with the least redundancy and duplicacy of data. 


  • Types of Normalization:
    • First Normal Form
    • Second Normal Form
    • Third Normal Form
    • BCNF - Boyce Code Normal Form
    • Fifth Normal Form
    • Sixth Normal Form : Impossible to achieve this level of normalization
  • First Normal Form
    • Eliminate repeating groups in individual tables. 
    • Create a separate table for each set of related data. 
    • Identify each set of related data with a primary key.
    • Example :  
             Lets Consider Unnormalized table 




Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble. 

 Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:


  • Second Normal Form
    • Create separate tables for sets of values that apply to multiple records. 
    • Relate these tables with a foreign key.
    • Example :
Note the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.

The following two tables demonstrate second normal form:

                 Students :


                  Registration:


  • Third Normal Form
    • Eliminate fields that do not depend on the key.
    • Example :
In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:

                  Students :


                   Faculty :



Difference between DBMS and RDBMS

  • database management system vs relational database management system /
Database Management System VS Relational Database Management System

• Relationship among tables is maintained in a RDBMS whereas this not the case DBMS as it is used to manage the database.

• DBMS accepts the ‘flat file’ data that means there is no relation among different data whereas RDBMS does not accepts this type of design.

• DBMS is used for simpler business applications whereas RDBMS is used for more complex applications.

• Although the foreign key concept is supported by both DBMS and RDBMS but its only RDBMS that enforces the rules.

• RDBMS solution is required by large sets of data whereas small sets of data can be managed by DBMS.

Wednesday, 16 January 2013

How to know request is ajax or other in php


How to know whether the request is an ajax request or normal request in PHP? 

We can know it through following code:

$ajax = false;

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
 $ajax = true;
}
echo $ajax;

Wednesday, 2 January 2013

All Gmail Shortcuts

First enable shortcuts of gmail
for that go to setting and find Keyboard shortcuts and on it

Jumping
g then i : Go to Inbox
g then s : Go to Starred conversations
g then t : Go to Sent messages
g then d : Go to Drafts
g then a : Go to All mail
g then c : Go to Contacts
g then k : Go to Tasks
g then l : Go to Label

Threadlist selection
* then a : Select all conversations
* then n : Deselect all conversations
* then r : Select read conversations
* then u : Select unread conversations
* then s : Select starred conversations
* then t : Select unstarred conversations

Navigation
u : Back to threadlist
k / j : Newer/older conversation
o or <Enter> : Open conversation; collapse/expand conversation
p / n : Read previous/next message
` : Go to next inbox section
~ : Go to previous inbox section

Application
c : Compose
/ : Search mail
q : Search chat contacts
. : Open "more actions" menu
v : Open "move to" menu
l : Open "label as" menu
? : Open keyboard shortcut help

Actions
, : Move focus to toolbar
x : Select conversation
s : Rotate superstar
y : Remove label
e : Archive
m : Ignore conversation
! : Report as spam
# : Move to trash
r : Reply
<Shift> + r : Reply in a new window
a : Reply all
<Shift> + a : Reply all in a new window
f : Forward
<Shift> + f : Forward in a new window
<Shift> + n : Update conversation
<Tab> then Enter : Send mail
<Esc> : Focus last mole
] / [ : Remove conversation from current view and go previous/next
} / { : Archive conversation and go previous/next
z : Undo last action
<Shift> + i : Mark as read
<Shift> + u : Mark as unread
_ : Mark unread from the selected message
<Ctrl> + s : Save draft
+ or = : Mark as important
- : Mark as not important
g then p : Make a phone call
<Shift> + t : Add conversation to Tasks

Sunday, 9 December 2012

regex ( regular expression ) for email, phone, number, time, postcodes, age, month, currency, text, swiss price, score, word count, profanity filter validation

SPECIAL NOTE: Regular Expressions in Conditions

Note - when using regular expressions in the condition editor, do NOT include the beginning and ending slash.

Email Validation:
                        
/(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})/

The above regex will not validate email adresses with "+" - which is valid, and e.g. promoted by gmail. The below regex is slightly modified and allows "+":

/^(\w[-._+\w]*\w@\w[-._\w]*\w\.\w{2,3})$/

It is still far from perfect - but I think its better then the original (also because start-of-string and end-of-string anchors are added). Mind. This will allow e.g. abc+++defg@somemail.office.com. Ideally the regex should be modified to only allow one "+" charachter.

Postcodes:

Australian Postcodes: 
/^[0-9]{4}/


Brazilian Postcodes:   /^[0-9]{2}\.[0-9]{3}-[0-9]{3}$/

Canadian Postcodes:  /^[a-zA-Z]\d{1}[a-zA-Z](\-| |)\d{1}[a-zA-Z]\d{1}$/

US Postal Codes:         /^[0-9]{5}([- /]?[0-9]{4})?$/

Phone Numbers:

US Phone Number:


/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/

or

/^[\(\)\.\- ]{0,}[0-9]{3}[\(\)\.\- ]{0,}[0-9]{3}[\(\)\.\- ]{0,}[0-9]{4}[\(\)\.\- ]{0,}$/

This second option will match all phone Canadian and US phone numbers that include non-digit symbols including
. ( ) - (space)

This will allow you to match phone numbers which resemble below.

(555)555 5555
555.555.5555
555 555 5555
(555)-555-5555
555-555-5555
555555555

Australian Phone Number:

The following patterns match all various Australian mobile and landline phone numbers including with "+61" country prefix eg:

(02) 9123 6535
03 1234-5345
0412 345 678
+61 2 3456 789

But not:

234 3450 234
a234 534 3432
134567
123456789013

Brackets, white space and hypens are ignored.

NOTE: The 'PRECICE' versions listed here match against the first four or five didgets in a number to ensure that they are valid Australian numbers. The 'NOT VERY PRECISE' only match against the first and second didgit so may allow invaid numbers

All Australian phone numbers (mobile and landline - area code required) :

VERY PRECISE
/^\(?(?:\+?61|0)(?:(?:2\)?[ -]?(?:3[ -]?[38]|[46-9][ -]?[0-9]|5[ -]?[0-35-9])|3\)?(?:4[ -]?[0-57-9]|[57-9][ -]?[0-9]|6[ -]?[1-67])|7\)?[ -]?(?:[2-4][ -]?[0-9]|5[ -]?[2-7]|7[ -]?6)|8\)?[ -]?(?:5[ -]?[1-4]|6[ -]?[0-8]|[7-9][ -]?[0-9]))(?:[ -]?[0-9]){6}|4\)?[ -]?(?:(?:[01][ -]?[0-9]|2[ -]?[0-57-9]|3[ -]?[1-9]|4[ -]?[7-9]|5[ -]?[018])[ -]?[0-9]|3[ -]?0[ -]?[0-5])(?:[ -]?[0-9]){5})$/ 

NOT VERY PRECISE 
/^(?:\+?61|0)[2-478](?:[ -]?[0-9]){8}$/

All Australian phone numbers (landlines only - area code required):

VERY PRECISE 
/^\(?(?:\+?61|0)(?:2\)?[ -]?(?:3[ -]?[38]|[46-9][ -]?[0-9]|5[ -]?[0-35-9])|3\)?(?:4[ -]?[0-57-9]|[57-9][ -]?[0-9]|6[ -]?[1-67])|7\)?[ -]?(?:[2-4][ -]?[0-9]|5[ -]?[2-7]|7[ -]?6)|8\)?[ -]?(?:5[ -]?[1-4]|6[ -]?[0-8]|[7-9][ -]?[0-9]))(?:[ -]?[0-9]){6}$/ 

NOT VERY PRECISE 
/^(?:\+?61|\(?0)[2378]\)?(?:[ -]?[0-9]){8}$/

New South Wales landline phone numbers (area code optional):

VERY PRECISE 
/^(?:\(?(?:\+?61|0)2\)?[ -]?)?(?:3[ -]?[38]|[46-9][ -]?[0-9]|5[ -]?[0-35-9])(?:[ -]?[0-9]){6}$/ 

NOT VERY PRECISE 
/^(?:\(?(?:\+?61|0)2\)?(?:[ -]?[0-9]){7}[0-9]$/

Victorian and Tasmanian landline phone numbers (area code optional):

VERY PRECISE 
/^(?:\(?(?:\+?61|0)3\)?[ -]?)?(?:4[ -]?[0-57-9]|[57-9][ -]?[0-9]|6[ -]?[1-67])(?:[ -]?[0-9]){6}$/ 

NOT VERY PRECISE 
/^(?:\(?(?:\+?61|0)3\)?(?:[ -]?[0-9]){7}[0-9]$/

Queensland landline phone numbers (area code optional):

VERY PRECISE 
/^(?:\(?(?:\+?61|0)7\)?[ -]?)?(?:[2-4][ -]?[0-9]|5[ -]?[2-7]|7[ -]?6)(?:[ -]?[0-9]){6}$/ 

NOT VERY PRECISE 
/^(?:\(?(?:\+?61|0)7\)?(?:[ -]?[0-9]){7}[0-9]$/

South Australia, Northern Territory, Western Australia landline phone numbers (area code optional):

VERY PRECISE 
/^(?:\(?(?:\+?61|0)8\)?[ -]?)?(?:5[1-4]|6[0-8]|[7-9][0-9])$/ 

NOT VERY PRECISE 
/^(?:\(?(?:\+?61|0)8\)?(?:[ -]?[0-9]){7}[0-9]$/

Australian Mobile phone numbers only

VERY PRECISE 
/^(?:\+?61|0)4 ?(?:(?:[01] ?[0-9]|2 ?[0-57-9]|3 ?[1-9]|4 ?[7-9]|5 ?[018]) ?[0-9]|3 ?0 ?[0-5])(?: ?[0-9]){5}$/ 

NOT VERY PRECISE 
/^(?:\(?(?:\+?61|0)4\)?(?:[ -]?[0-9]){7}[0-9]$/

Belgian phone number

/^((\+|00)32\s?|0)(\d\s?\d{3}|\d{2}\s?\d{2})(\s?\d{2}){2}$/

Belgian mobile phone number

/^((\+|00)32\s?|0)4(60|[789]\d)(\s?\d{2}){3}$/


French phone number

/^((\+|00)33\s?|0)[1-5](\s?\d{2}){4}$/


French mobile phone number

/^((\+|00)33\s?|0)[679](\s?\d{2}){4}$/


Luxemburg phone number

/^((\+|00\s?)352)?(\s?\d{2}){3,4}$/


Luxemburg mobile phone number

/^((\+|00\s?)352)?\s?6[269]1(\s?\d{3}){2}$/


German marks (with optional plus or minus)

/^[1-6]{1}[\+|\-]?$/


Age Validation:

Example: Age 20-99

/([2-9][0-9])/Example: Age 18-35
/(1[8-9]|2[0-9]|3[0-5])/

Example: Age 19-65

^(1[8-9]|[2-5][0-9]|6[0-5])$

Number validation:

Numbers from 1 to 99999

/^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9])$/
/^[1-9][0-9]{0,4}$/ does the same as above but should run a little faster

Numbers from 1 to 999, 1.000 to 999.999 to 999.999.999

/^[1-9][0-9]{0,2}(?:\.[0-9]{3}){0,2}$/ accepts numbers from 1 to 999, 1.000 to 999.999 to 999.999.999 but rejects numbers like 999.1.1 , 94.22.22, 999.1.22, 999.11.1, 999.1.333

Number validation with optionnal decimal (for price)

/^([1][0-9][0-9]|[1-9][0-9]|[0-9])((\.)[0-9][0-9])?$/ accepts numbers from 0 to 199, with 2 decimal optionnal

/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}\.[0-9]{2}$/ forces two decimal points accepts numbers from 1.00 to 999,999,999.00 with an optional comma delimiting thousands/millions including all of the following: 1.00, 1,000.00 , 12,345.67 , 12345,02 , 123,456,468.00 , 1234566.00 , 123456789.00 but not 1,23.00 , 12,3.4 or 1234,43.04
/^[1-9][0-9]{0,2}(?:,?[0-9]{3}){0,3}(?:\.[0-9]{2})?$/ same as above but the two decimal points are optional


Month (1-12)

If you want to ask for the month a person was born you can validate the input as follows:
/^[0]*[1-9]$|^[0]*1[0-2]$/


Minimum width (set to 3 in this example)

/^.{3,}$/


Currency

US currency (dollar sign and cents optional)

/^\$?\d+(\.(\d{2}))?$/

Swiss price

A number with two decimal numbers after the decimal point of which the last one is either a 5 or a 0:
/^(\d+)(\.\d(05)?)?$/

Validate score

1-10

/^[1-9]{1}$|^10$/

1-100

/^[1-9]?[0-9]{1}$|^100$/


Text validation

currently multiple short text doesn't support minimum or maximum answers. One way around this is to use a long free text type question with a regular expression.
The following test for at least one word per line for at least 3 lines and no more than 10 lines.

/(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+)*)(?:[,.;:?!& \n\r]?(?:\n|\r|\n\r|\r\n)(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+)*)){2,10}/is
If you wanted, say five words per line you could change the first and last star/asterisk to {4,} e.g.

/(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+){4,})(?:[,.;:?!& \n\r]?(?:\n|\r|\n\r|\r\n)(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+){4,})){2,10}/is
If you wanted one or more words per line on between 1 and 5 lines, you can change the content of the last curley braces to {0,4} (note you use 0 because you're already matching the first line.

/(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+)*)(?:[,.;:?!& \n\r]?(?:\n|\r|\n\r|\r\n)(?:[^,.;:?!& \n\r]+(?: [^,.;:?!& \n\r]+)*)){0,4}/is

Word count

The following restricts the number of words allowed to a minimum of 1 and a maximum of 200 

/^[-\w]+(?:\W+[-\w]+){0,199}\W*$/

To increase the minimum change the zero part of {0,199} 
To increase or decrease the maximum change the "199" part of {0,199}

Time validation

There are a number of ways of writing time formats. Some of the possible options are 12 hour or 24 hour, with seconds or without. regular expressions below:

The following three validation strings test for 24 hour time (in order of appearences) without seconds, with optional seconds lastly with seconds required. 

/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/ /^(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?$/ /^(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/

The following three match 12 hour time, as above with seconds, optional seconds and with seconds required 

/^(?:00:[0-5][0-9] (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9] (?:[ap]m|[AP]M)|12:[0-5][0-9] (?:pm|PM))$/ /^(?:00:[0-5][0-9](?::[0-5][0-9])? (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9](?::[0-5][0-9])? (?:[ap]m|[AP]M)|12:[0-5][0-9](?::[0-5][0-9])? (?:pm|PM))$/ /^(?:00:[0-5][0-9]:[0-5][0-9] (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9]:[0-5][0-9] (?:[ap]m|[AP]M)|12:[0-5][0-9]:[0-5][0-9] (?:pm|PM))$/
The following three match either 12 or 24 hour time as above with seconds, optional seconds and with seconds required 

/^(?:(?:00:[0-5][0-9] (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9] (?:[ap]m|[AP]M)|12:[0-5][0-9] (?:pm|PM))|(?:[01][0-9]|2[0-3]):[0-5][0-9])$/ /^(?:(?:00:[0-5][0-9](?::[0-5][0-9])? (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9](?::[0-5][0-9])? (?:[ap]m|[AP]M)|12:[0-5][0-9](?::[0-5][0-9])? (?:pm|PM))|(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?)$/ /^(?:(?:00:[0-5][0-9]:[0-5][0-9] (?:am|AM)|(?:0[1-9]|1[01]):[0-5][0-9]:[0-5][0-9] (?:[ap]m|[AP]M)|12:[0-5][0-9]:[0-5][0-9] (?:pm|PM))|(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])$/

US States

To validate for one state use the following (example is Texas):

TX uppercase only = /^(TX)$/
tx lowercase only = /^(tx)$/
TX upper or lowercase = /^([T|t][X|x])$/

Profanity Filter

To filter profanity words from an answer:
/^(?i)((?!\bENTERPROFANITYHERE\b).)*$(?-i)/

Replace "ENTERPROFANITYHERE" with your bad word.

The \b will allow passing of words such as "assassination" & "hello" if you enter "ass" or "hell" as your profanity word. This also works if you are trying to omit other words, names etc. from answers.