Let me summarize your question : "would it be reasonable/feasible for there to be a set of functions, generally accepted, uniform, and solid, that are basically the standard way to validate form data?"
If what I summarize is true, then the answer is : jQuery Validation. As the name stated, you need jQuery and jQuery Validation to make this work.
Below is an example on how to use this tools.
HTML :
<form id="myForm">
<input type="text" name="currency">
<input type="text" name="amount">
</form>
Javascript:
$("#myForm").validate({
rules: {
"currency": {
minlength: 3,
required: true
},
"amount": {
number: true
}
}
});
As default, validation is triggered on KeyUp. So when user change, lets say, field currency and broke one of the rules above, jQuery Validation will give pre-build notification message automatically.
These are the pre-build messages for rules above :
- minlength: Please enter at least three characters
- required: This field is required
- number: Please enter a valid number
What if you want to validate whether a currency is available in our exchange rate's table?
The answer is: just add custom Validation Method.
$.validator.addMethod("checkCurrency",
function(value, element) {
var result = false;
$.ajax({
type:"GET",
async: false,
url: "012_ajax.php", // script to validate in server side
data: {currency: value},
success: function(data) {
result = (data == "1") ? true : false;
}
});
// return true if currency is exist in database
return result;
},
"Currency is not exist."
);
$("#myForm").validate({
rules: {
"currency": {
minlength: 3,
required: true,
checkCurrency: true
},
"amount": {
number: true
}
}
});
With this code, everytime user entry unexist currency in table, form will always show "Currency is not exist" message.
Last question: could I create custom message for this plugin?
The answer is YES.
$("#myForm").validate({
rules: {
"currency": {
minlength: 3,
required: true,
checkCurrency: true
},
"amount": {
number: true
}
},
messages: {
"currency": {
minlength: "Currency should at least 3 char or more",
required: "Currency is required"
},
"amount": {
number: "Amount must be number"
}
}
});
Now everytime user broke rules above, form will gives messages as state in code above.
The important thing of this plugin, as every form validation should do, is that data will not be submitted as long as data are not verified. Well, as long as user is't turning-off / disable javascript from his browser. :)
UPDATE
The answer above is for client side validation.
For server side validation, there are PHP form validation scripts on internet, among them are :
- http://html-form-guide.com
- A Soares
They have build-in validation rules and user could add the custom ones.
Hopefully this help.