List Of All Jobs in a select box

Today i was working on a registration and i needed a list of all job available for my user to choose. What will most of us do when this happen? Search Google! After that i left with despite because i fail to find such resource. The next terrifying thing most developer look at is the list of job available on Wikipedia (it just keep on going, damnit). Imagining compiling the whole few hundred list of job just to get them into a select box. Well, you don't have to imagine because i already did it. Hence, you get the joy while i do the work. lol~

<select class="select" id="selectbox" name="selectbox">
		<option value="Athlete">Athlete</option>
		<option value="Accountant">Accountant</option>
		<option value="Actor">Actor</option>
		<option value="Actress">Actress</option>
		<option value="Administrator">Administrator</option>
		<option value="Aerospace Engineer">Aerospace Engineer</option>
		<option value="Air Traffic Controller">Air Traffic Controller</option>
		<option value="Ambassador">Ambassador</option>
		<option value="Anesthetist">Anesthetist</option>
		<option value="Anchorman">Anchorman</option>
		<option value="Animator">Animator</option>
		<option value="Animal trainer">Animal trainer</option>
		<option value="Archaeologist">Archaeologist</option>
		<option value="Architect">Architect</option>
		<option value="Artist">Artist</option>
		<option value="Astronaut">Astronaut</option>
		<option value="Astronomer">Astronomer</option>
		<option value="Athletic trainer">Athletic trainer</option>
		<option value="Attorney">Attorney</option>
		<option value="Author">Author</option>
		<option value="Army">Army</option>
		<option value="Brain Surgeon">Brain Surgeon</option>
		<option value="Baker">Baker</option>
		<option value="Bank teller">Bank teller</option>
		<option value="Banker">Banker</option>
		<option value="Barber">Barber</option>
		<option value="Barista">Barista</option>
		<option value="Barrister">Barrister</option>
		<option value="Bartender">Bartender</option>
		<option value="Babysitter">Babysitter</option>
		<option value="Beauty queen">Beauty queen</option>
		<option value="Beauty therapist">Beauty therapist</option>
		<option value="Beekeeper">Beekeeper</option>
		<option value="Blacksmith">Blacksmith</option>
		<option value="Boilermaker">Boilermaker</option>
		<option value="Bookkeeper">Bookkeeper</option>
		<option value="Bookseller">Bookseller</option>
		<option value="Brewer">Brewer</option>
		<option value="Butcher">Butcher</option>
		<option value="Butler">Butler</option>
		<option value="Builder">Builder</option>
		<option value="Cab driver">Cab driver</option>
		<option value="Calligrapher">Calligrapher</option>
		<option value="Cameraman">Cameraman</option>
		<option value="Car designer">Car designer</option>
		<option value="Cardiologist">Cardiologist</option>
		<option value="Carpenter">Carpenter</option>
		<option value="Cartoonist">Cartoonist</option>
		<option value="Cartographer">Cartographer</option>
		<option value="Cashier">Cashier</option>
		<option value="Cellist">Cellist</option>
		<option value="Chess player">Chess player</option>
		<option value="CIO (Chief Information Officer)">CIO (Chief Information Officer)</option>
		<option value="CEO (Chief Executive Officer)">CEO (Chief Executive Officer)</option>
		<option value="CTO (Chief Technology Officer)">CTO (Chief Technology Officer)</option>
		<option value="CFO (Chief Financial Officer)">CFO (Chief Financial Officer)</option>
		<option value="Chauffeur">Chauffeur</option>
		<option value="Cheesemaker">Cheesemaker</option>
		<option value="Cook)">Cook)</option>
		<option value="Chemist">Chemist</option>
		<option value="Chief of police">Chief of police</option>
		<option value="Chimney sweep">Chimney sweep</option>
		<option value="Civil servant">Civil servant</option>
		<option value="Civil engineer">Civil engineer</option>
		<option value="Clarinetist">Clarinetist</option>
		<option value="Cleaner">Cleaner</option>
		<option value="Clerk">Clerk</option>
		<option value="Clockmaker">Clockmaker</option>
		<option value="Coach">Coach</option>
		<option value="Coachman">Coachman</option>
		<option value="Coast guard">Coast guard</option>
		<option value="Cobbler">Cobbler</option>
		<option value="Columnist">Columnist</option>
		<option value="Comedian">Comedian</option>
		<option value="Company Secretary">Company Secretary</option>
		<option value="Compasssmith">Compasssmith</option>
		<option value="Composer">Composer</option>
		<option value="Computer programmer">Computer programmer</option>
		<option value="Conductor (music)">Conductor (music)</option>
		<option value="Construction engineer">Construction engineer</option>
		<option value="Construction worker">Construction worker</option>
		<option value="Consul">Consul</option>
		<option value="Consultant">Consultant</option>
		<option value="Contractor, general">Contractor, general</option>
		<option value="Coroner">Coroner</option>
		<option value="Corrector">Corrector</option>
		<option value="Cosmonaut">Cosmonaut</option>
		<option value="Costume Designer">Costume Designer</option>
		<option value="Courier">Courier</option>
		<option value="Cryptographer">Cryptographer</option>
		<option value="Currier">Currier</option>
		<option value="Customs officer">Customs officer</option>
		<option value="Dancer">Dancer</option>
		<option value="Dentist">Dentist</option>
		<option value="Deputy (law enforcement)">Deputy (law enforcement)</option>
		<option value="Dermatologist">Dermatologist</option>
		<option value="Designer/Developer">Designer/Developer</option>
		<option value="Detective">Detective</option>
		<option value="Dictator">Dictator</option>
		<option value="Disc jockey">Disc jockey</option>
		<option value="Diver">Diver</option>
		<option value="Doctor">Doctor</option>
		<option value="Dog walker">Dog walker</option>
		<option value="Doorman">Doorman</option>
		<option value="Dressmaker">Dressmaker</option>
		<option value="Ecologist">Ecologist</option>
		<option value="Economist">Economist</option>
		<option value="Editor">Editor</option>
		<option value="Electrical engineer">Electrical engineer</option>
		<option value="Electrician">Electrician</option>
		<option value="Elevator mechanic">Elevator mechanic</option>
		<option value="Engineer">Engineer</option>
		<option value="Engraver">Engraver</option>
		<option value="Entrepreneur">Entrepreneur</option>
		<option value="Environmental scientist">Environmental scientist</option>
		<option value="Executive manager">Executive manager</option>
		<option value="Exterminator">Exterminator</option>
		<option value="Falconer">Falconer</option>
		<option value="Farmer">Farmer</option>
		<option value="Farrier">Farrier</option>
		<option value="Fashion designer">Fashion designer</option>
		<option value="FBI Agent">FBI Agent</option>
		<option value="Film director">Film director</option>
		<option value="Film producer">Film producer</option>
		<option value="Financial adviser">Financial adviser</option>
		<option value="Fire marshal">Fire marshal</option>
		<option value="Fire Safety Officer">Fire Safety Officer</option>
		<option value="Firefighter">Firefighter</option>
		<option value="First Mate">First Mate</option>
		<option value="Fishmonger">Fishmonger</option>
		<option value="Fisherman">Fisherman</option>
		<option value="Fitter">Fitter</option>
		<option value="Flavorist">Flavorist</option>
		<option value="Fletcher">Fletcher</option>
		<option value="Flight attendant">Flight attendant</option>
		<option value="Flight instructor">Flight instructor</option>
		<option value="Florist">Florist</option>
		<option value="Flutist">Flutist</option>
		<option value="Food critic">Food critic</option>
		<option value="Footballer">Footballer</option>
		<option value="Forester">Forester</option>
		<option value="Fortune teller">Fortune teller</option>
		<option value="Funeral Director">Funeral Director</option>
		<option value="Gamekeeper">Gamekeeper</option>
		<option value="Game designer">Game designer</option>
		<option value="Gardener">Gardener</option>
		<option value="Gemcutter">Gemcutter</option>
		<option value="Genealogist">Genealogist</option>
		<option value="General">General</option>
		<option value="Geologist">Geologist</option>
		<option value="Goldsmith">Goldsmith</option>
		<option value="Government agent">Government agent</option>
		<option value="Governor">Governor</option>
		<option value="Graphic Designer">Graphic Designer</option>
		<option value="Gravedigger">Gravedigger</option>
		<option value="Greengrocer">Greengrocer</option>
		<option value="Grocer">Grocer</option>
		<option value="Guide">Guide</option>
		<option value="Guitarist">Guitarist</option>
		<option value="Gunsmith">Gunsmith</option>
		<option value="Harpist">Harpist</option>
		<option value="Handyman">Handyman</option>
		<option value="Hairdresser">Hairdresser</option>
		<option value="Harbourmaster">Harbourmaster</option>
		<option value="Harper">Harper</option>
		<option value="Hatter">Hatter</option>
		<option value="Historian">Historian</option>
		<option value="Homeopath">Homeopath</option>
		<option value="Hotel manager">Hotel manager</option>
		<option value="Housekeeper">Housekeeper</option>
		<option value="Hairstylist">Hairstylist</option>
		<option value="Human Resource Manager">Human Resource Manager</option>
		<option value="Human Resource Assistant">Human Resource Assistant</option>
		<option value="Illuminator">Illuminator</option>
		<option value="Illusionist">Illusionist</option>
		<option value="Illustrator">Illustrator</option>
		<option value="Importer">Importer</option>
		<option value="Industrial engineer">Industrial engineer</option>
		<option value="Industrialist">Industrialist</option>
		<option value="Information Technologist">Information Technologist</option>
		<option value="Information Designer">Information Designer</option>
		<option value="Inker">Inker</option>
		<option value="Innkeeper">Innkeeper</option>
		<option value="Instructor">Instructor</option>
		<option value="Interior designer">Interior designer</option>
		<option value="Interpreter">Interpreter</option>
		<option value="Interrogator">Interrogator</option>
		<option value="Inventor">Inventor</option>
		<option value="disambiguation needed">disambiguation needed</option>
		<option value="Investment banker">Investment banker</option>
		<option value="Investment broker">Investment broker</option>
		<option value="Ironmonger">Ironmonger</option>
		<option value="Ironmaster">Ironmaster</option>
		<option value="Ironworker">Ironworker</option>
		<option value="Jailer">Jailer</option>
		<option value="Janitor">Janitor</option>
		<option value="Jeweller">Jeweller</option>
		<option value="Journalist">Journalist</option>
		<option value="Jurist">Jurist</option>
		<option value="Judge">Judge</option>
		<option value="Jockey">Jockey</option>
		<option value="Joggler">Joggler</option>
		<option value="Karate master">Karate master</option>
		<option value="Kinesiologist">Kinesiologist</option>
		<option value="Laborer">Laborer</option>
		<option value="Landlady)">Landlady)</option>
		<option value="Lavendar)">Lavendar)</option>
		<option value="Law enforcement agent">Law enforcement agent</option>
		<option value="Lawyer">Lawyer</option>
		<option value="Leadworker">Leadworker</option>
		<option value="Leatherer">Leatherer</option>
		<option value="Leather worker">Leather worker</option>
		<option value="Lecturer">Lecturer</option>
		<option value="Level designer (also Mapper)">Level designer (also Mapper)</option>
		<option value="Librarianship">Librarianship</option>
		<option value="Librettist">Librettist</option>
		<option value="Lifeguard">Lifeguard</option>
		<option value="Lighthouse keeper">Lighthouse keeper</option>
		<option value="Lighting technician">Lighting technician</option>
		<option value="Lineman">Lineman</option>
		<option value="Linguist">Linguist</option>
		<option value="Loan officer">Loan officer</option>
		<option value="Lobbyist">Lobbyist</option>
		<option value="Locksmith">Locksmith</option>
		<option value="Lumberjack">Lumberjack</option>
		<option value="Lyricist">Lyricist</option>
		<option value="Magistrate">Magistrate</option>
		<option value="Magnate">Magnate</option>
		<option value="Maid">Maid</option>
		<option value="Mailman or Mail carrier">Mailman or Mail carrier</option>
		<option value="Make-up artist">Make-up artist</option>
		<option value="Management consultant">Management consultant</option>
		<option value="Manager">Manager</option>
		<option value="Manicurist">Manicurist</option>
		<option value="Manufacturer">Manufacturer</option>
		<option value="Marine">Marine</option>
		<option value="Marine biologist">Marine biologist</option>
		<option value="Market gardener">Market gardener</option>
		<option value="Martial artist">Martial artist</option>
		<option value="Mason">Mason</option>
		<option value="Master of business administration">Master of business administration</option>
		<option value="MC)">MC)</option>
		<option value="masseur)">masseur)</option>
		<option value="Matador">Matador</option>
		<option value="Mathematician">Mathematician</option>
		<option value="Mechanic">Mechanic</option>
		<option value="Mechanical Engineer">Mechanical Engineer</option>
		<option value="Mechanician">Mechanician</option>
		<option value="Mediator">Mediator</option>
		<option value="Medic">Medic</option>
		<option value="Medical biller">Medical biller</option>
		<option value="Medical Transcriptionist">Medical Transcriptionist</option>
		<option value="Mesmerist">Mesmerist</option>
		<option value="Messenger">Messenger</option>
		<option value="Mid-wife">Mid-wife</option>
		<option value="Milkmaid)">Milkmaid)</option>
		<option value="Miller">Miller</option>
		<option value="Miner">Miner</option>
		<option value="Missionary">Missionary</option>
		<option value="Model">Model</option>
		<option value="Modeller">Modeller</option>
		<option value="Moneychanger">Moneychanger</option>
		<option value="Moneylender">Moneylender</option>
		<option value="Monk">Monk</option>
		<option value="Mortgage broker">Mortgage broker</option>
		<option value="Mountaineer">Mountaineer</option>
		<option value="Muralist">Muralist</option>
		<option value="Musician">Musician</option>
		<option value="Navigator">Navigator</option>
		<option value="N??gociant">N??gociant</option>
		<option value="Negotiator">Negotiator</option>
		<option value="Netmaker">Netmaker</option>
		<option value="Neurologist">Neurologist</option>
		<option value="Newscaster">Newscaster</option>
		<option value="Night auditor">Night auditor</option>
		<option value="Nightwatchmen">Nightwatchmen</option>
		<option value="Notary">Notary</option>
		<option value="Novelist">Novelist</option>
		<option value="Numerologist">Numerologist</option>
		<option value="Numismatist">Numismatist</option>
		<option value="Nun">Nun</option>
		<option value="Nursemaid">Nursemaid</option>
		<option value="Nurse">Nurse</option>
		<option value="Nutritionist">Nutritionist</option>
		<option value="Oboist">Oboist</option>
		<option value="Obstetrician">Obstetrician</option>
		<option value="Occupational therapist">Occupational therapist</option>
		<option value="Odontologist">Odontologist</option>
		<option value="Oncologist">Oncologist</option>
		<option value="Ontologist">Ontologist</option>
		<option value="Operator">Operator</option>
		<option value="Ophthalmologist">Ophthalmologist</option>
		<option value="Optometrist)">Optometrist)</option>
		<option value="Oracle">Oracle</option>
		<option value="Ordinary Seaman">Ordinary Seaman</option>
		<option value="disambiguation needed">disambiguation needed</option>
		<option value="Orthodontist">Orthodontist</option>
		<option value="Ornithologist">Ornithologist</option>
		<option value="Ostler">Ostler</option>
		<option value="Otorhinolaryngologist">Otorhinolaryngologist</option>
		<option value="Optometrist">Optometrist</option>
		<option value="Ocularist">Ocularist</option>
		<option value="Opthamologist">Opthamologist</option>
		<option value="Painter">Painter</option>
		<option value="Paleontologist">Paleontologist</option>
		<option value="Paralegal">Paralegal</option>
		<option value="Paramedic">Paramedic</option>
		<option value="Park ranger">Park ranger</option>
		<option value="Parole Officer">Parole Officer</option>
		<option value="Pastor">Pastor</option>
		<option value="Patent attorney">Patent attorney</option>
		<option value="Patent examiner">Patent examiner</option>
		<option value="Pathologist">Pathologist</option>
		<option value="Pawnbroker">Pawnbroker</option>
		<option value="Peddler">Peddler</option>
		<option value="Pediatrician">Pediatrician</option>
		<option value="Pedologist (soil)">Pedologist (soil)</option>
		<option value="Percussionist">Percussionist</option>
		<option value="Perfumer">Perfumer</option>
		<option value="Personal Trainer">Personal Trainer</option>
		<option value="Pharmacist">Pharmacist</option>
		<option value="Philanthropist">Philanthropist</option>
		<option value="Philologist">Philologist</option>
		<option value="Philosopher">Philosopher</option>
		<option value="Photographer">Photographer</option>
		<option value="Photo Specialist">Photo Specialist</option>
		<option value="Physical Therapist">Physical Therapist</option>
		<option value="Physician">Physician</option>
		<option value="Physician Assistant">Physician Assistant</option>
		<option value="Physicist">Physicist</option>
		<option value="Physiognomist">Physiognomist</option>
		<option value="Physiotherapist">Physiotherapist</option>
		<option value="Pianist">Pianist</option>
		<option value="Piano tuner">Piano tuner</option>
		<option value="Pilot (shipping)">Pilot (shipping)</option>
		<option value="Pilot (aviation)">Pilot (aviation)</option>
		<option value="Pirate">Pirate</option>
		<option value="Plumber">Plumber</option>
		<option value="Podiatrist">Podiatrist</option>
		<option value="Poet">Poet</option>
		<option value="Police inspector">Police inspector</option>
		<option value="Politician">Politician</option>
		<option value="disambiguation needed">disambiguation needed</option>
		<option value="Presenter">Presenter</option>
		<option value="President">President</option>
		<option value="Press officer">Press officer</option>
		<option value="Priest">Priest</option>
		<option value="Princess">Princess</option>
		<option value="Principal">Principal</option>
		<option value="Printer">Printer</option>
		<option value="Private detective">Private detective</option>
		<option value="Probation Officer">Probation Officer</option>
		<option value="Proctologist">Proctologist</option>
		<option value="Product designer">Product designer</option>
		<option value="Professor">Professor</option>
		<option value="Professional dominant">Professional dominant</option>
		<option value="Programmer">Programmer</option>
		<option value="Project Manager">Project Manager</option>
		<option value="Proofreader">Proofreader</option>
		<option value="Psychiatrist">Psychiatrist</option>
		<option value="Psychodramatist">Psychodramatist</option>
		<option value="Psychologist">Psychologist</option>
		<option value="Public Relations Officer">Public Relations Officer</option>
		<option value="Public speaker">Public speaker</option>
		<option value="Publisher">Publisher</option>
		<option value="Porn star">Porn star</option>
		<option value="Queen consort">Queen consort</option>
		<option value="Queen regnant">Queen regnant</option>
		<option value="Quilter">Quilter</option>
		<option value="Radiologist">Radiologist</option>
		<option value="Radiographer">Radiographer</option>
		<option value="Real estate broker">Real estate broker</option>
		<option value="Real estate investor">Real estate investor</option>
		<option value="Real estate developer">Real estate developer</option>
		<option value="Receptionist">Receptionist</option>
		<option value="Record Producer">Record Producer</option>
		<option value="Referee">Referee</option>
		<option value="Refuse collector">Refuse collector</option>
		<option value="Registrar">Registrar</option>
		<option value="Reporter">Reporter</option>
		<option value="Researcher">Researcher</option>
		<option value="Respiratory Therapist">Respiratory Therapist</option>
		<option value="Restaurateur">Restaurateur</option>
		<option value="Retailer">Retailer</option>
		<option value="Rubbish Collector">Rubbish Collector</option>
		<option value="Sailmaker">Sailmaker</option>
		<option value="Sailor">Sailor</option>
		<option value="Salesmen">Salesmen</option>
		<option value="Sanitation worker">Sanitation worker</option>
		<option value="Saucier">Saucier</option>
		<option value="Saxophonist">Saxophonist</option>
		<option value="disambiguation needed">disambiguation needed</option>
		<option value="Scientist">Scientist</option>
		<option value="School superintendent">School superintendent</option>
		<option value="Scout">Scout</option>
		<option value="Screenwriter">Screenwriter</option>
		<option value="Scrivener)">Scrivener)</option>
		<option value="Seamstress">Seamstress</option>
		<option value="Second Mate">Second Mate</option>
		<option value="Secret service agent">Secret service agent</option>
		<option value="Secretary general">Secretary general</option>
		<option value="Security guard">Security guard</option>
		<option value="Senator">Senator</option>
		<option value="SEO (search engine optimizer)">SEO (search engine optimizer)</option>
		<option value="Sexton">Sexton</option>
		<option value="Sheepshearer">Sheepshearer</option>
		<option value="Sheriff">Sheriff</option>
		<option value="Sheriff officer">Sheriff officer</option>
		<option value="Shoemaker">Shoemaker</option>
		<option value="Shop assistant">Shop assistant</option>
		<option value="Singer">Singer</option>
		<option value="Skydiver">Skydiver</option>
		<option value="Sleeper">Sleeper</option>
		<option value="Sleuth">Sleuth</option>
		<option value="Social worker">Social worker</option>
		<option value="Socialite">Socialite</option>
		<option value="Software engineer">Software engineer</option>
		<option value="Soil scientist">Soil scientist</option>
		<option value="Soldier">Soldier</option>
		<option value="Solicitor">Solicitor</option>
		<option value="Sommelier">Sommelier</option>
		<option value="Sonographer">Sonographer</option>
		<option value="Sound Engineer">Sound Engineer</option>
		<option value="Special agent">Special agent</option>
		<option value="Speech therapist">Speech therapist</option>
		<option value="Sportsman">Sportsman</option>
		<option value="Spy">Spy</option>
		<option value="Statistician">Statistician</option>
		<option value="Street artist">Street artist</option>
		<option value="Street musician">Street musician</option>
		<option value="Stevedore">Stevedore</option>
		<option value="Street sweeper">Street sweeper</option>
		<option value="Street vendor">Street vendor</option>
		<option value="Structural engineers">Structural engineers</option>
		<option value="Stunt double">Stunt double</option>
		<option value="Stunt performer">Stunt performer</option>
		<option value="Surgeon">Surgeon</option>
		<option value="Supervisor">Supervisor</option>
		<option value="Surveyor">Surveyor</option>
		<option value="Swimmer">Swimmer</option>
		<option value="Switchboard operator">Switchboard operator</option>
		<option value="System administrator">System administrator</option>
		<option value="Systems analyst">Systems analyst</option>
		<option value="Student">Student</option>
		<option value="Tailor">Tailor</option>
		<option value="Tanner">Tanner</option>
		<option value="Tapester)">Tapester)</option>
		<option value="Tax Collector">Tax Collector</option>
		<option value="Tax Lawyer">Tax Lawyer</option>
		<option value="Taxidermist">Taxidermist</option>
		<option value="Taxicab driver">Taxicab driver</option>
		<option value="Taxonomist">Taxonomist</option>
		<option value="Tea lady">Tea lady</option>
		<option value="Teacher">Teacher</option>
		<option value="Technician">Technician</option>
		<option value="Technologist">Technologist</option>
		<option value="Technical Writer">Technical Writer</option>
		<option value="Telegraph operator)">Telegraph operator)</option>
		<option value="Telephone operator">Telephone operator</option>
		<option value="Tennis player">Tennis player</option>
		<option value="Test developer">Test developer</option>
		<option value="Test pilot">Test pilot</option>
		<option value="Torchwood Officer">Torchwood Officer</option>
		<option value="Thatcher">Thatcher</option>
		<option value="Theatre director">Theatre director</option>
		<option value="Therapist">Therapist</option>
		<option value="Thimbler">Thimbler</option>
		<option value="Tiler">Tiler</option>
		<option value="Toolmaker">Toolmaker</option>
		<option value="Trademark attorney">Trademark attorney</option>
		<option value="Trader">Trader</option>
		<option value="Tradesman">Tradesman</option>
		<option value="Trainer (business)">Trainer (business)</option>
		<option value="Transit planner">Transit planner</option>
		<option value="Translator">Translator</option>
		<option value="Treasurer">Treasurer</option>
		<option value="Truck Driver">Truck Driver</option>
		<option value="Turner">Turner</option>
		<option value="Tutor">Tutor</option>
		<option value="Tyler">Tyler</option>
		<option value="Typist">Typist</option>
		<option value="Undertaker">Undertaker</option>
		<option value="Ufologist">Ufologist</option>
		<option value="Undercover agent">Undercover agent</option>
		<option value="Underwriter">Underwriter</option>
		<option value="Upholsterer">Upholsterer</option>
		<option value="Urologist">Urologist</option>
		<option value="Usher">Usher</option>
		<option value="Underwear model">Underwear model</option>
		<option value="Valet">Valet</option>
		<option value="Verger">Verger</option>
		<option value="Veterinarian">Veterinarian</option>
		<option value="Vibraphonist">Vibraphonist</option>
		<option value="Vicar">Vicar</option>
		<option value="Video editor">Video editor</option>
		<option value="Video game developer">Video game developer</option>
		<option value="Vintner">Vintner</option>
		<option value="Violinist">Violinist</option>
		<option value="Violist">Violist</option>
		<option value="Voice Actor">Voice Actor</option>
		<option value="Waitress)">Waitress)</option>
		<option value="disambiguation needed">disambiguation needed</option>
		<option value="Watchmaker">Watchmaker</option>
		<option value="Weaponsmith">Weaponsmith</option>
		<option value="Weatherman">Weatherman</option>
		<option value="Weaver">Weaver</option>
		<option value="Web designer">Web designer</option>
		<option value="Web developer">Web developer</option>
		<option value="Wedding Planner">Wedding Planner</option>
		<option value="Welder">Welder</option>
		<option value="Wet nurse">Wet nurse</option>
		<option value="Woodcarver">Woodcarver</option>
		<option value="Wood cutter">Wood cutter</option>
		<option value="Wrangler">Wrangler</option>
		<option value="Winemaker">Winemaker</option>
		<option value="Writer">Writer</option>
		<option value="Xylophonist">Xylophonist</option>
		<option value="Yodeler">Yodeler</option>
		<option value="Zookeeper">Zookeeper</option>
		<option value="Zoologist">Zoologist</option>
	</select>

Enjoy 🙂

Update:

I notice the above is pretty hard to find which has been previously selected by the user. Hence, i place them into an array and put it up here hopefully someone will find it useful for a list of all jobs in a php array 🙂

<select class="select" id="user_job" name="user_job">
		<option value=""> - Job - </option>
		<?php
			$loop = array('Athlete',		'Accountant',		'Actor',		'Actress',		'Administrator',		'Aerospace Engineer',		'Air Traffic Controller',		'Ambassador',		'Anesthetist',		'Anchorman',		'Animator',		'Animal trainer',		'Archaeologist',		'Architect',		'Artist',		'Astronaut',		'Astronomer',		'Athletic trainer',		'Attorney',		'Author',		'Army',		'Brain Surgeon',		'Baker',		'Bank teller',		'Banker',		'Barber',		'Barista',		'Barrister',		'Bartender',		'Babysitter',		'Beauty queen',		'Beauty therapist',		'Beekeeper',		'Blacksmith',		'Boilermaker',		'Bookkeeper',		'Bookseller',		'Brewer',		'Butcher',		'Butler',		'Builder',		'Cab driver',		'Calligrapher',		'Cameraman',		'Car designer',		'Cardiologist',		'Carpenter',		'Cartoonist',		'Cartographer',		'Cashier',		'Cellist',		'Chess player',		'CIO (Chief Information Officer)',		'CEO (Chief Executive Officer)',		'CTO (Chief Technology Officer)',		'CFO (Chief Financial Officer)',		'Chauffeur',		'Cheesemaker',		'Cook)',		'Chemist',		'Chief of police',		'Chimney sweep',		'Civil servant',		'Civil engineer',		'Clarinetist',		'Cleaner',		'Clerk',		'Clockmaker',		'Coach',		'Coachman',		'Coast guard',		'Cobbler',		'Columnist',		'Comedian',		'Company Secretary',		'Compasssmith',		'Composer',		'Computer programmer',		'Conductor (music)',		'Construction engineer',		'Construction worker',		'Consul',		'Consultant',		'Contractor, general',		'Coroner',		'Corrector',		'Cosmonaut',		'Costume Designer',		'Courier',		'Cryptographer',		'Currier',		'Customs officer',		'Dancer',		'Dentist',		'Deputy (law enforcement)',		'Dermatologist',		'Designer/Developer',		'Detective',		'Dictator',		'Disc jockey',		'Diver',		'Doctor',		'Dog walker',		'Doorman',		'Dressmaker',		'Ecologist',		'Economist',		'Editor',		'Electrical engineer',		'Electrician',		'Elevator mechanic',		'Engineer',		'Engraver',		'Entrepreneur',		'Environmental scientist',		'Executive manager',		'Exterminator',		'Falconer',		'Farmer',		'Farrier',		'Fashion designer',		'FBI Agent',		'Film director',		'Film producer',		'Financial adviser',		'Fire marshal',		'Fire Safety Officer',		'Firefighter',		'First Mate',		'Fishmonger',		'Fisherman',		'Fitter',		'Flavorist',		'Fletcher',		'Flight attendant',		'Flight instructor',		'Florist',		'Flutist',		'Food critic',		'Footballer',		'Forester',		'Fortune teller',		'Funeral Director',		'Gamekeeper',		'Game designer',		'Gardener',		'Gemcutter',		'Genealogist',		'General',		'Geologist',		'Goldsmith',		'Government agent',		'Governor',		'Graphic Designer',		'Gravedigger',		'Greengrocer',		'Grocer',		'Guide',		'Guitarist',		'Gunsmith',		'Harpist',		'Handyman',		'Hairdresser',		'Harbourmaster',		'Harper',		'Hatter',		'Historian',		'Homeopath',		'Hotel manager',		'Housekeeper',		'Hairstylist',		'Human Resource Manager',		'Human Resource Assistant',		'Illuminator',		'Illusionist',		'Illustrator',		'Importer',		'Industrial engineer',		'Industrialist',		'Information Technologist',		'Information Designer',		'Inker',		'Innkeeper',		'Instructor',		'Interior designer',		'Interpreter',		'Interrogator',		'Inventor',		'disambiguation needed',		'Investment banker',		'Investment broker',		'Ironmonger',		'Ironmaster',		'Ironworker',		'Jailer',		'Janitor',		'Jeweller',		'Journalist',		'Jurist',		'Judge',		'Jockey',		'Joggler',		'Karate master',		'Kinesiologist',		'Laborer',		'Landlady)',		'Lavendar)',		'Law enforcement agent',		'Lawyer',		'Leadworker',		'Leatherer',		'Leather worker',		'Lecturer',		'Level designer (also Mapper)',		'Librarianship',		'Librettist',		'Lifeguard',		'Lighthouse keeper',		'Lighting technician',		'Lineman',		'Linguist',		'Loan officer',		'Lobbyist',		'Locksmith',		'Lumberjack',		'Lyricist',		'Magistrate',		'Magnate',		'Maid',		'Mailman or Mail carrier',		'Make-up artist',		'Management consultant',		'Manager',		'Manicurist',		'Manufacturer',		'Marine',		'Marine biologist',		'Market gardener',		'Martial artist',		'Mason',		'Master of business administration',		'MC)',		'masseur)',		'Matador',		'Mathematician',		'Mechanic',		'Mechanical Engineer',		'Mechanician',		'Mediator',		'Medic',		'Medical biller',		'Medical Transcriptionist',		'Mesmerist',		'Messenger',		'Mid-wife',		'Milkmaid)',		'Miller',		'Miner',		'Missionary',		'Model',		'Modeller',		'Moneychanger',		'Moneylender',		'Monk',		'Mortgage broker',		'Mountaineer',		'Muralist',		'Musician',		'Navigator',		'N??gociant',		'Negotiator',		'Netmaker',		'Neurologist',		'Newscaster',		'Night auditor',		'Nightwatchmen',		'Notary',		'Novelist',		'Numerologist',		'Numismatist',		'Nun',		'Nursemaid',		'Nurse',		'Nutritionist',		'Oboist',		'Obstetrician',		'Occupational therapist',		'Odontologist',		'Oncologist',		'Ontologist',		'Operator',		'Ophthalmologist',		'Optometrist)',		'Oracle',		'Ordinary Seaman',		'disambiguation needed',		'Orthodontist',		'Ornithologist',		'Ostler',		'Otorhinolaryngologist',		'Optometrist',		'Ocularist',		'Opthamologist',		'Painter',		'Paleontologist',		'Paralegal',		'Paramedic',		'Park ranger',		'Parole Officer',		'Pastor',		'Patent attorney',		'Patent examiner',		'Pathologist',		'Pawnbroker',		'Peddler',		'Pediatrician',		'Pedologist (soil)',		'Percussionist',		'Perfumer',		'Personal Trainer',		'Pharmacist',		'Philanthropist',		'Philologist',		'Philosopher',		'Photographer',		'Photo Specialist',		'Physical Therapist',		'Physician',		'Physician Assistant',		'Physicist',		'Physiognomist',		'Physiotherapist',		'Pianist',		'Piano tuner',		'Pilot (shipping)',		'Pilot (aviation)',		'Pirate',		'Plumber',		'Podiatrist',		'Poet',		'Police inspector',		'Politician',		'disambiguation needed',		'Presenter',		'President',		'Press officer',		'Priest',		'Princess',		'Principal',		'Printer',		'Private detective',		'Probation Officer',		'Proctologist',		'Product designer',		'Professor',		'Professional dominant',		'Programmer',		'Project Manager',		'Proofreader',		'Psychiatrist',		'Psychodramatist',		'Psychologist',		'Public Relations Officer',		'Public speaker',		'Publisher',		'Porn star',		'Queen consort',		'Queen regnant',		'Quilter',		'Radiologist',		'Radiographer',		'Real estate broker',		'Real estate investor',		'Real estate developer',		'Receptionist',		'Record Producer',		'Referee',		'Refuse collector',		'Registrar',		'Reporter',		'Researcher',		'Respiratory Therapist',		'Restaurateur',		'Retailer',		'Rubbish Collector',		'Sailmaker',		'Sailor',		'Salesmen',		'Sanitation worker',		'Saucier',		'Saxophonist',		'disambiguation needed',		'Scientist',		'School superintendent',		'Scout',		'Screenwriter',		'Scrivener)',		'Seamstress',		'Second Mate',		'Secret service agent',		'Secretary general',		'Security guard',		'Senator',		'SEO (search engine optimizer)',		'Sexton',		'Sheepshearer',		'Sheriff',		'Sheriff officer',		'Shoemaker',		'Shop assistant',		'Singer',		'Skydiver',		'Sleeper',		'Sleuth',		'Social worker',		'Socialite',		'Software engineer',		'Soil scientist',		'Soldier',		'Solicitor',		'Sommelier',		'Sonographer',		'Sound Engineer',		'Special agent',		'Speech therapist',		'Sportsman',		'Spy',		'Statistician',		'Street artist',		'Street musician',		'Stevedore',		'Street sweeper',		'Street vendor',		'Structural engineers',		'Stunt double',		'Stunt performer',		'Surgeon',		'Supervisor',		'Surveyor',		'Swimmer',		'Switchboard operator',		'System administrator',		'Systems analyst',		'Student',		'Tailor',		'Tanner',		'Tapester)',		'Tax Collector',		'Tax Lawyer',		'Taxidermist',		'Taxicab driver',		'Taxonomist',		'Tea lady',		'Teacher',		'Technician',		'Technologist',		'Technical Writer',		'Telegraph operator)',		'Telephone operator',		'Tennis player',		'Test developer',		'Test pilot',		'Torchwood Officer',		'Thatcher',		'Theatre director',		'Therapist',		'Thimbler',		'Tiler',		'Toolmaker',		'Trademark attorney',		'Trader',		'Tradesman',		'Trainer (business)',		'Transit planner',		'Translator',		'Treasurer',		'Truck Driver',		'Turner',		'Tutor',		'Tyler',		'Typist',		'Undertaker',		'Ufologist',		'Undercover agent',		'Underwriter',		'Upholsterer',		'Urologist',		'Usher',		'Underwear model',		'Valet',		'Verger',		'Veterinarian',		'Vibraphonist',		'Vicar',		'Video editor',		'Video game developer',		'Vintner',		'Violinist',		'Violist',		'Voice Actor',		'Waitress)',		'disambiguation needed',		'Watchmaker',		'Weaponsmith',		'Weatherman',		'Weaver',		'Web designer',		'Web developer',		'Wedding Planner',		'Welder',		'Wet nurse',		'Woodcarver',		'Wood cutter',		'Wrangler',		'Winemaker',		'Writer',		'Xylophonist',		'Yodeler',		'Zookeeper',		'Zoologist');
			foreach($loop as $value){
				if($_POST['user_job'] == $value )
				echo '<option value="'.$value.'" selected>'.$value.'</option>';
				else
				echo '<option value="'.$value.'">'.$value.'</option>';
			}
		?>
	</select>

17 JavaScript Form Validation Snippets

Last week i wrote 25 form validation for PHP. I find useful to have more layer of defend as JavaScript might malfunction or disable and cause your validation to fail but the form is still being passed on to our server. Nonetheless, JavaScript validation does provide certain level of restriction and protection for any web application. Especially when web is evolving quickly in this period of time. We are required to validate any data from our user to prevent any harm that can cause damage to our application and businesses. These JavaScript form validation snippets are needed in every form validation and repeating searching for them is unnecessary and slow down development processes. Therefore, you might want to bookmark these snippets for your future needs

Email Validation

Email validation is the most basic validation that any web application would have.

function isEmail(elem, helperMsg){
	var regexp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(regexp.test(elem.value)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var email = document.getElementById('ham_email');
if(isEmail(email, "Invalid Email Format")){
//proceed..
}

URL Validation

URL validation helps to validate whether a particular string is a valid url format.

function isUrl(elem, helperMsg) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	if(regexp.test(elem.value.toLowerCase())){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var link = document.getElementById('ham_link');
if(isUrl(link, "Invalid link")){
//proceed..
}

Username Validation

This function help us validate whether a username contain valid character and length. It accept any underscore, alphabets and numbers within 5-25 characters.

function isValidUsername(elem, msg) {
	var regx = /^[A-Za-z0-9_]{5,25}$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

You can add additional symbols or change the length of the validation easily by alter the regular expression.

In order to use this, we pass in an object and an alert value if it fail.

var username = document.getElementById('username');
if(isValidUsername(username, "Invalid character found on username!")){
//proceed...
}

Password Validation

Here is a simple password strength validation that check the following criteria.

  1. Passwords will contain at least 1 upper case letter
  2. Passwords will contain at least 1 lower case letter
  3. Passwords will contain at least 1 number or special character
  4. Passwords will contain at least 8 characters in length
  5. Password maximum length should not be arbitrarily limited
function isStrongPassword(elem, msg) {
	var regx = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var password = document.getElementById('password');
if(isStrongPassword(password, "Your password fail the basic strength test. \n1. Passwords will contain at least 1 upper case letter\n2. Passwords will contain at least 1 lower case letter\n3. Passwords will contain at least 1 number or special character\n4. Passwords will contain at least 8 characters in length\n5. Password maximum length should not be arbitrarily limited\n")){
//proceed..
}

Numeric Validation

This validate whether a given string contain a valid numeric value which include both negative value and decimal ones.

function isNumeric(elem, helperMsg){
	var numericExpression = /^[-]?\d*\.?\d*$/;
	if(elem.value.toString().match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var price = document.getElementById('price');
if(isNumeric(price, "Invalid value found")){
//proceed...
}

Text Empty Validation

In every form validation, there is always a need to check whether a particular text box is empty.

function isEmpty(elem, helperMsg){
	if(elem.value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var name = document.getElementById('ham_company');
if(!isEmpty(name, "Please give us your name")){
//proceed...
}

Radio Box Validation

We can determine whether a radio box has been selected using this function.

function hasSelected(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

Drop Down Validation

We also check whether a particular drop down box has its value selected with the following function.
In order to use this, we pass in an object and an alert value if it fail.

var radio = document.getElementById('radio');
if(hasSelected(radio, Please select your gender")){
//proceed...
}
function isSelected(elem, helperMsg){
	if(elem.options[elem.selectedIndex].value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var month = document.getElementById('ham_month');
if(isSelected(month, "Please select a month")){
//proceed...
}

Check Box Validation

We can perform check box validation to see whether a particular check box has been selected through this function.

function hasChecked(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var checkbox= document. getElementsByName('checkbox');
if(checkPhone(checkbox, "Please tick one of the check box")){
//proceed...
}

Phone Validation

This function will validate the following criteria phone number.

  • phone:
    339-4248
    339-42-48
    339 42 48
    339 4248
    3394248
    (095) #phone#
    (095)#phone#
    +7 (095) #phone#
    +7 (095)#phone#
    +7(095) #phone#
    +7(095)#phone#
function checkPhone(elem, msg)
{
	var str = elem.value;
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
	if (str.match(phone2)) {
   		return true;
 	} else {
 		alert(helperMsg);
		elem.focus();
		return false;
 	}
}

In order to use this, we pass in an object and an alert value if it fail.

var phonenumber = document.getElementById('phonenumber');
if(checkPhone(phonenumber, "Invalid Phone Number")){
//proceed...
}

File Extension Validation

This function validate whether a particular upload string contains a valid extension.

function isAllowedFileExtension(elem, helperMsg){
	var alphaExp = /.*\.(gif)|(jpeg)|(jpg)|(png)$/;
	if(elem.value != "")
	{
		if(elem.value.toLowerCase().match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	else
		return true;
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var upload = document.getElementById('ham_upload');
if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")){
//proceed...
}

IP Validation

Sometimes there is a need to validate whether a particular IP address is valid using JavaScript.

function isValidIPAddress(elem, msg) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   ipaddr = elem.value.toLowerCase();
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 255) { return false; }
      }
      return true;
   } else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var ip= document.getElementById('ip');
if(isValidIPAddress(ip, "Invalid IP Address")){
//proceed...
}

US Social Security Number Validation

Testing US Social security number can be done with the below function.

function isValidSSN(elem, msg) {
	var value = elem.value.toLowerCase();
	var tmp = false;
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    if (!re.test(value)) { tmp = true; }
    var temp = value;
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
    if (temp.substring(0, 3) == "000") { tmp = true; }
    if (temp.substring(3, 5) == "00") { tmp = true; }
    if (temp.substring(5, 9) == "0000") { tmp = true; }

	if(tmp){
		alert(helperMsg);
		elem.focus();
		return false;
	}else
    return true;
}

In order to use this, we pass in an object and an alert value if it fail.

var ssn = document.getElementById('ssn');
if(isValidSSN(ssn, "Invalid US Social Security Number")){
//proceed...
}

US Zip Code Validation

We can valid US zip code using the following function.

function isValidZipCode(elem, msg) {
   var re = /^\d{5}([\-]\d{4})?$/;
   var value = elem.value.toLowerCase();
   if(re.test(value)){
		return true;
   }else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var zip= document.getElementById('zip');
if(isValidSSN(zip, "Invalid US Zip Code")){
//proceed...
}

Date Validation

This function validate date with a given format.

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || _
      (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else _
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else _
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else _
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

You will use the function this way,

if (!isValidDate(myDateString, "DMY")) { alert("The date is not in the correct format."); }

Time Validation

This function validate time such as

  1. 02:25AM
  2. 00:23PM
  3. 23:45PM
  4. 11:23
  5. etc.
function isValidTime(value) {
   var hasMeridian = false;
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/;
   if (!re.test(value)) { return false; }
   if (value.toLowerCase().indexOf("p") != -1) { hasMeridian = true; }
   if (value.toLowerCase().indexOf("a") != -1) { hasMeridian = true; }
   var values = value.split(":");
   if ( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) { return false; }
   }
   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; }
   if (values.length > 2) {
      if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { return false; }
   }
   return true;
}

Credit Card Validation

This function validate whether a given string format is similar to a credit card type.

function isValidCreditCard(type, ccnum) {
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

Summary

Usually i will use these code in such a way to validate my form. I find it neat and tidy.

form.onsubmit = validation;
var validation = function(){
	var name = document.getElementById('ham_company');
	var email = document.getElementById('ham_email');
	var link = document.getElementById('ham_link');
	var description = document.getElementById('ham_desc');
	var banner = document.getElementById('ham_banner');
	var month = document.getElementById('ham_month');
	var url = document.getElementById('ham_url');
	var upload = document.getElementById('ham_upload');
	var quiz = document.getElementById('ham_quiz');
	if(isEmail(email, "Invalid Email Format"))
		if(isUrl(link, "Invalid link"))
			if(OneNotEmpty(url, upload, "Either image url or upload must be perform!"))
				if(isAllowedFileExtension(url, "Please provide an image with Gif, Png or Jpg extension Only"))
					if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only"))
						if(isSelected(month, "Please select a month"))
							if(isSelected(banner, "Please select a banner"))
								if(NotEmpty(quiz, "Please answer the quiz"))
									if(NotEmpty(name, "Please give us your name"))
									{
										return true;
									}

	return false;
}

On the other hand, you can always brings up new form validation snippets to share with me in this article. I will love to know 🙂

Inline, Internal or External CSS Style Print First?

It is a common thing for most web beginners to wonder which style will the browser print first when we declare multiple style. Although i have explain previous on the order priority of CSS, i forgotten about the importance of inline, internal and external CSS style that both designers and developers might wonder when they started on web.

Inline CSS

The inline CSS also refer as embedded style is usually mark as the highest priority over internal or external style. An inline style has the highest priority among others but the style can only be apply to an individual element. Here's an example

<div style='height:200px;width:200px;text-align:center;'>Click me!</div>

Inline style may be convenient to write but maintenance work will definitely kill you one day.

External CSS

The external CSS which the style is usually placed on an external file will usually have the lowest priority over these three type.

<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">

Nonetheless, sometimes external CSS can have higher priority over the internal CSS in some circumstances.

Internal CSS

Internal CSS are definition declare inside of the HTML document with the style tag,

<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>

Internal CSS usually have the second highest priority among them. However, it will lose its priority if the external stylesheet declaration is placed at after the internal CSS. Hence,

<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">
<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>

the internal CSS is after the external CSS. Therefore, the internal CSS has a higher priority. On the other hand,

<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>
<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">

when the external CSS is after the internal CSS, the external CSS will have a higher priority.

Priority Sequences

Hence, we can produce a priority sequences of how CSS prioritize our CSS types.

  1. User Style
  2. Inline Style (inside HTML tag)
  3. Internal Style (usually on the HTML head section)
  4. External Style
  5. Browser Default Style

User style (the style that user define for your website) have the highest priority over all other types but as a developer or designer we should only worry about the priority given on inline, internal and external style. Nonetheless, it is also important to know that using !important will also mean that user style priority is overwrite by the HIGHEST priority (which is style declare with !important). That is also the reason why we should try to avoid the use of !important as a developer or designer to avoid any usability problem and utilize order priority in CSS.

Summary

Once we understand how order priority work in CSS, we can easily figure out how CSS cascade all our different styles into one. But one last thing to take note of. The order priority in this link only apply to internal and external style. Hence, if both internal and external have the same exact style definition which order priority in this link will CSS take as the highest priority. The answer lays in this article where we explain on the internal CSS section.

Best way to log details. Database or file log?

Unlike many articles in Hungred Dot Com where i share valuable web development information with my readers, this article is something that required everyone to debate on. Every system will require a logging system (unless it is a crappy system). Regardless is transaction log, result log, database log, error log and etc., there is always a need have a quick, secure and reliable log to store these information for any further investigation. And logging details usually fall into file or database category. We need to look at three important thing to consider a media to log our details. There are performance, security and reliability. Let me elaborate the importance of each point.

Log Performance

Performance, performance performance! This is something we all want to know about. Whether file base log or database log is better? We will be looking at long run where our log gets really huge! Delay and performance problem might arise and which media will be more resistance against such problem. Another good thing to consider between these two media is the extra cost of HTTP request comparing to a read and write and the problem of delay arise from huge size. We won't want to consider the alternative media only after the problem appear don't we?

Log Security

Another thing that every hacker will be interested with is the log file. Valuable information is being stored in our log file and it is necessary to consider how secure can either media gives us. Log file may even carry sensitive details of our customers which was log by our program. Hence, considering the security risk of having plain text and a database is important to prevent security hole in our system environment. Each media will have its own way to further secure its media but which is better?

Log Reliability

Why we bother to have a log file if it is unreliable. This is necessary for a system that is required to keep track of a system that handle important transaction. An unreliable log might miss a log due to various reason such as manual query termination, file lock, database down during logging and etc. It is necessary to have all our log in order to capture important incidents.

Other log criteria

Scalability and flexibility is another thing some of you might want to mention. Migration of server and ease of searching etc. is also points that is important for us to consider as a log that cannot find its detail is consider a useless log.

Database Logging

Performance wise, database might be slower when log amount is small. But once the log amount became a huge amount, database based logging might really be much faster. The problem i can see is that it will fight with other urgent query which has higher priority to be executed and table locking. This is usually resolve by using MySQL Insert Delay operation. Another issue will be latency which cause the delay o of the logging operation. In term of searching database logging surely have the upper hand. Security of the log depends solely on the security of the server and database. There might be risk of SQL injection but usually this should be taken care of by the developers.

In term of reliability, using insert delay will risk the chances of our log getting lost especially if the system is a very active one. In a very busy system every few millisecond time interval there will be additional query that makes the database super busy until the insert delay log are pile up and have to wait till the database is quiet to be active. Hence, any accident such my sql die or forcefully terminated, the log query are gone. Furthermore, additional overhead to delay such insert will degrade MySQL performance by a little.

Log file

Log file is the simplest way to achieve a logging system. Its basically just a few lines of code (depend how paranoid logger are you).  While the greatest advantage is its simplicity, the worst problem of file based logging is searching. Most developers who move to file based logging end up not relaying on logs. But usually this can be overcome with some formatting and regular expression. Performance wise, it should be directly opposite a database logging where smaller size will be better and larger it gets worst. Nonetheless,  theoretically both should be the same in term of opening and closing of file regardless of size. It should be solve easily by utilizing buffer. In term of security, file based logging usually uses plain text file. Knowing the name of the log file is equivalence to exposing to the public (especially open source apps). But this is usually resolve using file permission setting.

Unlike database logging, file based logging doesn't required a call to the database. Hence, everything is done by the server scripting language you are using and operation is complete regardless of whether the connection is down(as long as the request pass from client to server is complete).

The other more critical part to choose file based logging is the problem of file locking where only one person is allowed to open the log file at one time. Hence, in a active system this might really post a big problem where logging is done intensively. The most expensive part in file based logging should be searching. Hence, regular expression can be really handy (or pain in the ass).

Summary

Some uses both file based logging and database logging with a little help from a external batch program. But it really depends on the need and required of your logging system. But my job here is done; I have started the fire. Now its time to heat it up. 😀

25 PHP Form Validation Snippets

Recently i have involve myself in another application development. Regular Hungred Dot Com visitors will notice that the site currently offer advertisement space through this form. But really, we as a developers are always looking for such snippets or writing them out from scratch every single time regardless of how many time we know we have store it somewhere in our laptop! Man, its really frustrating searching on Google and find all sort of solution and trying to figure out whether the regular expression implemented is expensive or complete. So i came out with an idea to ease my life a bit and other developers by putting up an article such as this for my/our references. (This can be made into a class if you like to)

Validate Email

We can perform an email validation through this function.

	function isValidEmail($email){
		return eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email);
	}

After fainted for a few seconds when i saw unreal4u finding, i decided to throw up preg_match solution instead.

	function isValidEmail($email){
		return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $email);
	}

PHP 5.2 and above.

function fnValidateEmail($email)
{
  return filter_var($email, FILTER_VALIDATE_EMAIL);
}

Sanitize Email

We can further sanitize our email to ensure that everything is alright.

function fnSanitizeEmaill($string) {
     return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
}

PHP 5.2 and above.

function fnSanitizeEmaill($url)
{
  return filter_var($url, FILTER_SANITIZE_EMAIL);
}

Validate Email Exist

This is not possible but certain validation can be use to validate email existence.

function check_email($email)
{
	$email_error = false;
	$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
	if ($Email == '') { email_error = true; }
	elseif (!eregi('^([a-zA-Z0-9._-])[email protected]([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+', $Email)) { email_error = true; }
	else {
	list($Email, $domain) = split('@', $Email, 2);
		if (! checkdnsrr($domain, 'MX')) { email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode('@', $array);
		}
	}

	if (email_error) { return false; } else{return true;}
}

Validate Number Only

We can use PHP built-in function to validate whether a given value is a number.

function fnValidateNumber($value)
{
	#is_ double($value);
	#is_ float($value);
	#is_ int($value);
	#is_ integer($value);
	return is_numeric($value);
}

PHP 5.2 and above.

function fnValidateNumber($value)
{
	#return filter_var($value, FILTER_VALIDATE_FLOAT); // float
	return filter_var($value, FILTER_VALIDATE_INT); # int
}

Sanitize Number

We can force all value to be only numeric by sanitize them.

function fnSanitizeNumber($str)
{
	#letters and space only
	return preg_match('/[^0-9]/', '', $str);
}

PHP 5.2 and above.

function fnSanitizeNumber($value)
{
	#return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT); // float
	return filter_var($value, FILTER_SANITIZE_NUMBER_INT); # int
}

Validate String Only

Sometimes to validate name we can use this function to restrict only letters and spaces.

function fnValidateStringr($str)
{
	#letters and space only
	return preg_match('/^[A-Za-z\s ]+$/', $str);
}

Sanitize String

We can sanitize it instead of validate user input.

function fnSanitizeStringr($str)
{
	#letters and space only
	return preg_replace('/[^A-Za-z\s ]/', '', $str);
}

PHP 5.2 and above. built-in function by PHP provides a much more powerful sanitize capability.

function fnSanitizeStringr($str)
{
	return filter_var($str, FILTER_SANITIZE_STRIPPED); # only 'String' is allowed eg. '<br>HELLO</br>' => 'HELLO'
}

Validate Alphanumeric Characters

This validates alphanumeric characters.

function fnValidateAlphanumeric($string)
{
	return ctype_alnum ($string);
}

Sanitize Alphanumeric Characters

This sanitize alphanumeric characters. eg. "HELLO! Do we have 90 idiots running around here?" => "HELLO Do we have 90 idiots running around here"

function fnSanitizeAlphanumeric($string)
{
	return preg_replace('/[^a-zA-Z0-9]/', '', $string);
}

Validate URL Exist

This function will check whether a given URL exist and not only validate it.

	function url_exist($url)
	{
		$url = @parse_url($url);

		if (!$url)
		{
			return false;
		}

		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';

		if ($path == '')
		{
			$path = '/';
		}

		$path .= (isset($url['query'])) ? '?$url[query]' : '';

		if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
		{
			if (PHP_VERSION >= 5)
			{
				$headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

				if (!$fp)
				{
					return false;
				}
				fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
				$headers = fread($fp, 4096);
				fclose($fp);
			}
			$headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
			return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
		}
		return false;
	}

Validate URL Format

This function will validate a given url to ensure the format is correct.

function fnValidateUrl($url){
return preg_match('/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i', $url);
}

PHP 5.2 and above.

function fnValidateUrl($url)
{
  return filter_var($url, FILTER_VALIDATE_URL);
}

Sanitize URL

PHP 5.2 and above.

function fnSanitizeUrl($url)
{
  return filter_var($url, FILTER_SANITIZE_URL);
}

Validate Image Exist

This function will check whether a given image link exist and not only validate it.

	function image_exist($url) {
	if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
	}

Validate IP Address

This function will validate an IP address.

function fnValidateIP($IP){
	return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
}

PHP 5 and above. This can also specific validation for IPV4 or IPV6.

function fnValidateIP($ip)
{
  return filter_var($ip, FILTER_VALIDATE_IP);
}

Validate Proxy

This function will let us detect proxy visitors even those that are behind anonymous proxy.

function fnValidateProxy(){
	if ($_SERVER['HTTP_X_FORWARDED_FOR']
	   || $_SERVER['HTTP_X_FORWARDED']
	   || $_SERVER['HTTP_FORWARDED_FOR']
	   || $_SERVER['HTTP_VIA']
	   || in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
	   || @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
	{
		exit('Proxy detected');
	}
}

Validate Username

Before we validate whether a given username is matches the one in our database, we can perform a validation check first to prevent any unnecessary SQL call.

function fnValidateUsername($username){
	#alphabet, digit, @, _ and . are allow. Minimum 6 character. Maximum 50 characters (email address may be more)
	return preg_match('/^[a-zA-Z\[email protected]]{6,50}$/i', $username);
}

Validate Strong Password

Another good thing is to validate whether a particular password given by the user is strong enough. You can do that using this function which required the password to have a minimum of 8 characters, at least 1 uppercase, 1 lowercase and 1 number.

function fnValidatePassword($password){
	#must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
	return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
}

Validate US Phone Number

This function will validate US phone number for US users.

function fnValidateUSPhone($phoneNo){
	return preg_match('/\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}/x', $phoneNo);
}

Validate US Postal Code

This function validate US postal code.

function fnValidateUSPostal($postalcode){
	#eg. 92345-3214
	return preg_match('/^([0-9]{5})(-[0-9]{4})?$/i',$postalcode);
}

Validate US Social Security Numbers

This function validate US Social Security Numbers.

function fnValidateUSSocialSecurityCode($ssb){
	#eg. 531-63-5334
	return preg_match('/^[\d]{3}-[\d]{2}-[\d]{4}$/',$ssn);
}

Validate Credit Card

This function validate credit card format.

function fnValidateCreditCard($cc){
	#eg. 718486746312031
	return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
}

Validate Date

This is a date format MM-DD-YYYY or MM-DD-YY validation which validate from year 0000-9999.

function fnValidateDate($date){
	#05/12/2109
	#05-12-0009
	#05.12.9909
	#05.12.99
	return preg_match('/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.][0-9]?[0-9]?[0-9]{2})*$/', $date);
}

This is a date format YYYY-DD-MM or YY-MM-DD validation which validate from year 0000-9999.

function fnValidateDate($date){
	#2009/12/11
	#2009-12-11
	#2009.12.11
	#09.12.11
	return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#'', $date);
}

Validate Hexadecimal Colors

This is a good validation for people who allows their user to change color in their system.

function fnValidateColor($color){
	#CCC
	#CCCCC
	#FFFFF
	return preg_match('/^#(?:(?:[a-f0-9]{3}){1,2})$/i', $color);
}

Make Query Safe

This function help sanitize our data to be SQL injection safe.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..

Make Data Safe

This function help to keep us protected against XSS, JS and SQL injection by removing tags.

function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str), ENT_QUOTES))));
}

//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..

Summary

A paranoid way to perform a form validation would be to validate first then sanitize your values for precautions. If you think the above snippets were suck or you have any good or awesome snippets to share. Please throw your comment and share with us!