Validate process starts from form design
Very often we will need to create or update some forms before committing them to the backend.
Even before we create forms, keep open text fields to a mininum. Often, it is good to let the user select from predefine lists, radio choices, etc.
Validations both in backend and frontend
Validations of fields should be done on both frontend and backend. Alot of people implement validations on the frontend only. When someone uses postman or intercept the request and consume the APIs directly, it will create chaos in the database.
Common validations & code snippets
Some of the common validation checks are as follows:
- Mandatory
//validate mandatory
Core_Utils.validateMandatory = function(value) {
if (!value) {
return true;
} else {
return false;
}
}
- Numeric
Core_Utils.isNumeric = function(value) {
return !isNaN(value);
}
- Email Format
//Validate Email
Core_Utils.validateEmail = function(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
- Minimum & Maximum Length Check
//Length Check
Core_Utils.validateLength = function(value, min, max) {
if ((value>=min) && (value<max)) {
return true;
} else {
return false;
}
}
- Whether field contains special characters
//Check whether content is safe
/*
< (open angle parenthesis)
> (close angle parenthesis)
• ' (single apostrophe)
• " (quotation mark)
• \' (backslash-escaped apostrophe)
• \" (backslash-escaped quotation mark)
• ( (opening parenthesis)
• ) (closing parenthesis)
• ; (semicolon)
• % (percentage)
*/
Core_Utils.isSanitized = function(content) {
if (content!="") {
var regex = /<|>|\'|\"|\(|\)|;|%/g;
return !regex.test(content);
}
return true;
}
- JSON content
//Check whether string is JSON
Core_Utils.isJson = function(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
- IP Address
//validate Ip address
Core_Utils.validateIPaddress = function(ipaddress) {
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {
return true;
}
return false;
}
- Version (major.minor.variant format)
//validate version
Core_Utils.validateVersion = function(version) {
if (/^\d{1,2}\.\d{1,2}\.\d{1,2}$/.test(version)) {
return true;
} else {
return false;
}
}
Validation real-time or upon submit?
Personally, its more user friendly to display error message in real-time as the user types.
Happy Coding!
Top comments (0)