VMax Form Validator javascript library

Purpouse

This script is designed to simplify validation of HTML forms userinput. Easy to use library allows you to specify rules for each element in form. When check is failed specified for this field alert will be shown and focus will be passed to form element which caused problems. And all this with minimum Javascript coding.

Compatibility

Netscape 4 or higher Microsoft Internet Explorer 4 or higher.

Creating HTML form

Nothing special, one can create HTML form as usual. All what needed is that all elements in form which requires validation must be named. Let's take as example something like this:
<form action="some.cgi" onSubmit="checkForm(this,rules); return false;">
<input type="text"   name="field1" size="20">
<input type="text"   name="field2" size="20">
<input type="submit" value="Go!">
</form>

Linking library

Add the following code just after <HEAD> tag of the HTML document

<script src="vmaxformvalidator.js">
<script>
  var myrules=new Array();
  // here later we will define rules for  
  // each element which requires validation
</script>

Creating rules

On previous step we already created array myrules. Now we need to create rules itself. For text elements we can do it so: (add this lines to script where we reserved place for it)
 myrules["field1"]=new rule(true,/^[a-z]*$/,"only a-z lowercase characters allowed here"); 
 myrules["field2"]=new rule(true,/^\d*$/,"only digits allowed here"); 
Well, we create associative array. Index in this array is string and must match form element name to which this rule belongs. This is used to get rules from array just by field name while validation. Now few words about rule(...) constructor. It have 3 parameters. First parameter have meaning "required", when it's true then for successfull validation field value MUST present, empty value not allowed. When "required" is false validation always will be successfull if field left empty.
Second parameter is regular expression to validate form element. More precisely this parameter must be regexp for text,textarea and password elements, for types select, radio and checkbox meaning of this second parameter is different (see below).
Last parameter is text for alert to show up when check of this element fails.
Please note that RegExps need to be designed correctly if you want correct result. For example this regexp
myrules["field2"]=new rule(true,/^\d*$/g,"only digits allowed here");
match when the whole string from the begining to end contains any number of digits So it match either whole string either none, this is OK and correct. But something like this:
myrules["field2"]=new rule(true,/\d*/g,"only digits allowed here");
Will match to any string ! That's defenetly wrong..
I'm not guru in RegExps, so at the end of this page I have added form to edit and test regexps. When you (like me) are not guru in regexps, this form will be helpfull for trying various variants.

Adding onSubmit handler

Add onSubmit handler to FORM element
onSubmit="return checkForm(this,myrules);"
checkForm() function will return true or false as validation result and when it return false form wouldn't be submitted. "This" in context of onSubmit form handler contains reference to form element and myrules is array of rules for validation of the form.
Now example form will looks like:
<form action="some.cgi" onSubmit="return checkForm(this,myrules);">
<input type="text"   name="field1" size="20">
<input type="text"   name="field2" size="20">
<input type="submit" value="Go!">
</form>

Time to test our example

Note, it's slightly modified as we do not need to submit test form instead it will just notify you when validation is ok.



List of supported input types and meanings of rule constructor parameters

TEXT,
TEXTAREA,
PASSWORD




HTML code:
<input type="text" name="txt">
<textarea name="ta"></textarea>
<INPUT TYPE="password" NAME="pwd">
   
rules[formElementName]=new rule(required,RegExp,alertText)

required - boolean value indicating can field be left blank or not
RegExp - regular expression to check field
alerttext - text for alert when check failed.

JavaScript Example:

   
CHECKBOX


HTML code:
<INPUT TYPE="checkbox" NAME="ch">
rules[formElementName]=new rule(required,requiredState,alertText)

required - boolean value indicating can field be left blank or not
requiredState - required state on checkbox ( true or flase ) 
alerttext - text for alert when check failed.

JavaScript Example:

   
SELECT,
SELECT-multiple, RADIO




R&B Soul Rock Blues

HTML code:
<select name="sel">
 <option >none
 <option value="a">a
 <option value="b">b
</select>

<select name="selmul" MULTIPLE>
 <option >none
 <option value="a">a
 <option value="b">b
</select>

<INPUT TYPE="radio" NAME="rad">R&B
<INPUT TYPE="radio" NAME="rad">Soul
<INPUT TYPE="radio" NAME="rad">Rock
<INPUT TYPE="radio" NAME="rad">Blues
rules[formElementName]=new rule(required,null,alertText)

required - boolean value indicating that at least one item with non-null value must be selected
null - always null ( this field not used for this input types )
alerttext - text for alert when check failed.

JavaScript Example:

   

Limitations

The only unsupported type is "FILE". Due to security reasons most browsers do not allow scripts to get it's value, so it can't be validated. When you will find some other field types it's missing, just let me know.

Browser Compatibility

Netscape 4 or higher, Microsoft Internet Explorer 5 or higher

Terms of use

This library and it's derivatives is free for use for noncommercial pupouses only, until this notice remains unchanged and present in all copies and derivatives.

Download

vmaxformvalidator.zip

Regular Expressions

If you are familiar with regular expressions, then you do not need to read this.. When not then it might be helpfull.
In general in this script regular expression used as pattern for string to check. In javascript regular expression can be constructed as following

/pattern/flags;

Where flags are one of the following or none Pattern generaly is set of characters where some characters or it's combinations have special meanings.
For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.

-or-

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more a's. To match * literally, precede the it with a backslash; for example, /a\*/ matches 'a*'.

^ Matches beginning of input or line.

For example, /^A/ does not match the 'A' in "an A," but does match it in "An A."

$ Matches end of input or line.

For example, /t$/ does not match the 't' in "eater", but does match it in "eat"

* Matches the preceding character 0 or more times.

For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled", but nothing in "A goat grunted".

+ Matches the preceding character 1 or more times. Equivalent to {1,}.

For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy."

? Matches the preceding character 0 or 1 time.

For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."

. (The decimal point) matches any single character except the newline character.

For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.

(x) Matches 'x' and remembers the match.

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n], or from the predefined RegExp object's properties $1, ..., $9.

x|y Matches either 'x' or 'y'.

For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."

{n} Where n is a positive integer. Matches exactly n occurrences of the preceding character.

For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in "caandy," and the first two a's in "caaandy."

{n,} Where n is a positive integer. Matches at least n occurrences of the preceding character.

For example, /a{2,} doesn't match the 'a' in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy."

{n,m} Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding character.

For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the first two a's in "caandy," and the first three a's in "caaaaaaandy" Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more a's in it.

[xyz] A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen.

For example, [abcd] is the same as [a-c]. They match the 'b' in "brisket" and the 'c' in "ache".

[^xyz] A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.

For example, [^abc] is the same as [^a-c]. They initially match 'r' in "brisket" and 'h' in "chop."

[\b] Matches a backspace. (Not to be confused with \b.)

\b Matches a word boundary, such as a space. (Not to be confused with [\b].)

For example, /\bn\w/ matches the 'no' in "noonday";/\wy\b/ matches the 'ly' in "possibly yesterday."

\B Matches a non-word boundary.

For example, /\w\Bn/ matches 'on' in "noonday", and /y\B\w/ matches 'ye' in "possibly yesterday."

\cX Where X is a control character. Matches a control character in a string.

For example, /\cM/ matches control-M in a string.

\d Matches a digit character. Equivalent to [0-9].

For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."

\D Matches any non-digit character. Equivalent to [^0-9].

For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."

\f Matches a form-feed.

\n Matches a linefeed.

\r Matches a carriage return.

\s Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v].

for example, /\s\w*/ matches ' bar' in "foo bar."

\S Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v].

For example, /\S/\w* matches 'foo' in "foo bar."

\t Matches a tab

\v Matches a vertical tab.

\w Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_].

For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."

\W Matches any non-word character. Equivalent to [^A-Za-z0-9_].

For example, /\W/ or /[^$A-Za-z0-9_]/ matches '%' in "50%."

\n Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

For example, /apple(,)\sorange\1/ matches 'apple, orange', in "apple, orange, cherry, peach." A more complete example follows this table.

Note: If the number of left parentheses is less than the number specified in \n, the \n is taken as an octal escape as described in the next row.

\ooctal
\xhex
Where \ooctal is an octal escape value or \xhex is a hexadecimal escape value. Allows you to embed ASCII codes into regular expressions.

More details on Regular expressions can be found almost in any Perl language book or tutorial.

Create your RegExps

Just to simplify development one can use this form to create regular expression and test it against test string.
RegExp : / /
Test String :
Result :
[result will be matching part of test string or array of matches]
[result will be regular expression java script code.]

©2002 Virtual Max