@@ -66,36 +69,18 @@ Next, inside an item, there will typically be an input or select or something of
The whole approach here is to define each form field (input, select, whatever) as much as possible with HTML5 attributes and also with custom attributes.
**required attribute**
Defines that this field should be validated (with JS by my implementation and not via native HTML5 browser defaults)
| required | Defines that this field should be validated (with JS by my implementation and not via native HTML5 browser defaults) |
| placeholder | Writes some placeholder text which usually describes the fields with some example input (not supported in IE8 and below) |
| pattern | Defines a pattern which the field is evaluated with. Available values are:<br>**numeric** - Allow only numbers<br>**alphanumeric** - Allow only numbers or letters. No special language characters<br>**phone** - Allow only numbers, spaces or dashes.<br><br>Alternatively, you may write your own custom regex here as well. |
| data-validate-words | Defines the minimum amount of words for this field |
| data-validate-length | Defines the length allowed for the field (after trim). Example value: `7,11` (field can only have 7 or 11 characters). you can add how many allowed lengths you wish |
| data-validate-length-range | Defines the minimum and/or maximum number of chars in the field (after trim). value can be `4,8` for example, or just `4` to set minimum chars only |
| data-validate-linked | Defines the field which the current field’s value (the attribute is set on) should be compared to |
| data-validate-minmax | For type `number` only. Defines the minimum and/or maximum value that can be in that field |
**placeholder attribute**
Writes some placeholder text which usually describes the fields with some example input (not supported in IE8 and below)
**data-validate-words custom attribute**
Defines the minimum amount of words for this field
**data-validate-length custom attribute**
Defines the length allowed for the field (after trim). Example value: “7,11″ (field can only have 7 or 11 characters). you can add how many allowed lengths you wish
**data-validate-length-range custom attribute**
Defines the minimum and/or maximum number of chars in the field (after trim). value can be “4,8″ for example, or just “4″ to set minimum chars only
**data-validate-linked custom attribute**
Defines the field which the current field’s value (the attribute is set on) should be compared to
**data-validate-minmax custom attribute**
For type ‘number’ only. Defines the minimum and/or maximum value that can be in that field.
**data-validate-pattern custom attribute**
Defines a pattern which the field is evaluated with. Available values are:
*numeric* - Allow only numbers
*alphanumeric* - Allow only numbers or letters. No special language characters
*phone* - Allow only numbers, spaces or dashes
aleternativly, you can write your own custom regex here as well.
### Optional fields
...
...
@@ -104,7 +89,8 @@ There is also support for optional fields, which are not validated, unless they
## Error messages
The validator function holds a messages object called ‘message’, which itself holds all the error messages being shown to the user for all sort of validation errors.
The validator function holds a messages object called "message", which itself holds all the error messages being shown to the user for all sort of validation errors.
message = {
invalid : 'invalid input',
empty : 'please put something here',
...
...
@@ -121,11 +107,11 @@ The validator function holds a messages object called ‘message’, which itsel
complete : 'input is not complete',
select : 'Please select an option'
};
This object can be extended easily. The idea is to extend it with new keys which represent the name of the field you want the message to be linked to, and that custom message appear as the ‘general error’ one. Default messages can be over-ride.
This object can be extended easily. The idea is to extend it with new keys which represent the name of the field you want the message to be linked to, and that custom message appear as the `general error` one. Default messages can be over-ride.
Example: for a given type ‘date’ field, lets set a custom (general error) message like so:
`validator.message['date'] = 'not a real date';`
Error messages can be disabled:
`validator.defaults.alerts = false;`
...
...
@@ -133,32 +119,40 @@ Error messages can be disabled:
There are 2 ways to validate form fields, one is on the submit event of the form itself, then all the fields are evaluated one by one. The other method is by binding the ‘checkField’ function itself to each field, for events like “Blur”, “Change” or whatever event you wish (I prefer on Blur).
###Example - 1
###Usage example - validate on submit
A generic callback function using jQuery to have the form validated on the **Submit** event. You can also include your own personal validations before the **checkAll()** call.
A generic callback function using jQuery to have the form validated on the “Submit” event. You can also include your own personal validations before the **checkAll()** call.
$('form').submit(function(e){
e.preventDefault();
var submit = true;
// you can put your own custom validations below
// check all the rerquired fields
if( !validator().checkAll( $(this) ) )
// check all the rerquired fields
if( !validator.checkAll( $(this) ) )
submit = false;
if( submit )
this.submit();
return false;
})
###Example - 2
Check every field once it looses focus (onBlur) event (using jQuery 1.7.1 new ‘on’ method which is like the old .deligate() in this case).
The helper tooltips **<div class='tooltip help'>**, which work using pure CSS, are element which holds a small **'?'** icon and when hovered over with the mouse, reveals a text explaining what the field “item” is about or for example, what the allowed input format is.
## Classes
`validator.defaults.classes` object can be modified with these classes:
// if hit Backspace key when caret was at the beginning, or if the 'left' arrow key was pressed and the caret was at the start -> go back to previous field
varvalidator=(function(){varmessage,tests,checkField,validate,mark,unmark,field,minmax,defaults,validateWords,lengthRange,lengthLimit,pattern,alertTxt,data,email_illegalChars=/[\(\)\<\>\,\;\:\\\/\"\[\]]/,email_filter=/^.+@.+\..{2,3}$/;message={invalid:"invalid input",empty:"please put something here",min:"input is too short",max:"input is too long",number_min:"too low",number_max:"too high",url:"invalid URL",number:"not a number",email:"email address is invalid",email_repeat:"emails do not match",password_repeat:"passwords do not match",repeat:"no match",complete:"input is not complete",select:"Please select an option"};defaults={alerts:true};tests={sameAsPlaceholder:function(a){return$.fn.placeholder&&a.attr("placeholder")!==undefined&&data.val==a.prop("placeholder")},hasValue:function(a){if(!a){alertTxt=message.empty;returnfalse}returntrue},linked:function(a,b){if(b!=a){alertTxt=message[data.type+"_repeat"]||message.no_match;returnfalse}returntrue},email:function(a){if(!email_filter.test(a)||a.match(email_illegalChars)){alertTxt=a?message.email:message.empty;returnfalse}returntrue},text:function(a){if(validateWords){varwords=a.split("");varwordsLength=function(len){for(varw=words.length;w--;){if(words[w].length<len){returnfalse}}returntrue};if(words.length<validateWords||!wordsLength(2)){alertTxt=message.complete;returnfalse}returntrue}if(a.length<lengthRange[0]){alertTxt=message.min;returnfalse}if(lengthRange[1]&&a.length>lengthRange[1]){alertTxt=message.max;returnfalse}if(lengthLimit.length){varobeyLimit=false;while(lengthLimit.length){if(lengthLimit.pop()==a.length){obeyLimit=true}}if(!obeyLimit){alertTxt=message.complete;returnfalse}}if(pattern){varregex;switch(pattern){case"alphanumeric":regex=/^[a-z0-9]+$/i;break;case"numeric":regex=/^[0-9]+$/i;break;case"phone":regex=/^\+?([0-9]|[-|' '])+$/i;break;default:regex=pattern}try{if(regex&&!eval(regex).test(a)){returnfalse}}catch(err){console.log(err,field,"regex is invalid");returnfalse}}returntrue},number:function(a){if(isNaN(parseFloat(a))&&!isFinite(a)){alertTxt=message.number;returnfalse}else{if(a.length<lengthRange[0]){alertTxt=message.min;returnfalse}else{if(lengthRange[1]&&a.length>lengthRange[1]){alertTxt=message.max;returnfalse}else{if(minmax[0]&&(a|0)<minmax[0]){alertTxt=message.number_min;returnfalse}else{if(minmax[1]&&(a|0)>minmax[1]){alertTxt=message.number_max;returnfalse}}}}}returntrue},date:function(a){varday,A=a.split(/[-./]/g),i;if(field[0].valueAsNumber){returntrue}for(i=A.length;i--;){if(isNaN(parseFloat(a))&&!isFinite(a)){returnfalse}}try{day=newDate(A[2],A[1]-1,A[0]);if(day.getMonth()+1==A[1]&&day.getDate()==A[0]){returnday}returnfalse}catch(er){console.log("date test: ",err);returnfalse}},url:function(a){functiontestUrl(url){return/^(https?:\/\/)?([\w\d\-_]+\.+[A-Za-z]{2,})+\/?/.test(url)}if(!testUrl(a)){console.log(a);alertTxt=a?message.url:message.empty;returnfalse}returntrue},hidden:function(a){if(a.length<lengthRange[0]){alertTxt=message.min;returnfalse}if(pattern){varregex;if(pattern=="alphanumeric"){regex=/^[a-z0-9]+$/i;if(!regex.test(a)){returnfalse}}}returntrue},select:function(a){if(!tests.hasValue(a)){alertTxt=message.select;returnfalse}returntrue}};mark=function(field,text){if(!text||!field||!field.length){returnfalse}varitem=field.parents(".item"),warning;item.find(".alert").remove();if(defaults.alerts){warning=$("<div>").addClass("alert").text(text);item.append(warning)}item.removeClass("bad");setTimeout(function(){item.addClass("bad")},0)};unmark=function(field){if(!field||!field.length){console.warn('no "field" argument, null or DOM object not found');returnfalse}field.parents(".item").removeClass("bad").find(".alert").animate({marginLeft:32,opacity:0},200,function(){$(this).remove()})};functioncheckField(){field=$(this);if(field[0].type!="hidden"&&field.is(":hidden")){returntrue}field.data("valid",true);field.data("type",field.attr("type"));field.data("val",field[0].value.replace(/^\s+|\s+$/g,""));data=field.data();varv=data.val;alertTxt=message[field.prop("name")]||message.invalid;if(field[0].nodeName.toLowerCase()==="select"){data.type="select"}if(field[0].nodeName.toLowerCase()==="textarea"){data.type="text"}validateWords=data.validateWords||0;lengthRange=data.validateLengthRange?(data.validateLengthRange+"").split(","):[1];lengthLimit=data.validateLength?(data.validateLength+"").split(","):false;minmax=data.validateMinmax?(data.validateMinmax+"").split(","):"";pattern=data.validatePattern;if(tests.sameAsPlaceholder(field)){alertTxt=msg.form.empty;data.valid=false}if(data.validateLinked){varlinkedTo=data.validateLinked.indexOf("#")==0?$(data.validateLinked):$(":input[name="+data.validateLinked+"]");data.valid=tests.linked(v,linkedTo.val())}if(data.valid&&(data.valid=tests.hasValue(v))||data.type=="select"){switch(data.type){case"email":data.valid=tests.email(v);break;case"text":data.valid=tests.text(v);break;case"tel":pattern=pattern||"phone";data.valid=tests.text(v);break;case"password":data.valid=tests.text(v);break;case"number":data.valid=tests.number(v);break;case"date":data.valid=tests.date(v);break;case"url":data.valid=tests.url(v);break;case"select":data.valid=tests.select(v);break;case"hidden":data.valid=tests.hidden(v);break}}if(field.hasClass("optional")&&!data.val){data.valid=true}if(data.valid){unmark(field)}else{mark(field,alertTxt);submit=false}returndata.valid}functioncheckAll($form){if($form.length==0){console.warn("element not found");returnfalse}varthat=this,submit=true,fieldsToCheck=$form.find(":input").filter("[required=required], .required, .optional").not("[disabled=disabled]");fieldsToCheck.each(function(){submit=submit*checkField.apply(this)});return!!submit}return{defaults:defaults,checkField:checkField,checkAll:checkAll,mark:mark,unmark:unmark,message:message,tests:tests}})();