Validating Common Form Input - Part 2
Published on 5th of March 2010. Copyright Tavs Dokkedahl. Displayed 1978 time(s)Validating a username
A username is typically made of of alphanumeric characters - that is letters a - z and digits 0 - 9. It can be either lower or uppercase characters. For many reasons the username is often restricted to not contain special characters like $, #, £ etc.
Usernames are also restricted to a certain length as they have to fit into a fixed size database column. Finally the username often can not contain spaces.
To validate a username which can only contain letters in lowercase and can be no longer than 16 characters we can do
1 function validate(form) { 2 // Regular expression for username 3 var rgx = /^[a-z]{0,16}$/; 4 if(!rgx.test(form.elements.username.value)) 5 return false; 6 return true; 7 }
Don't worry too much if you are mystified by the regular expression - it is not as difficult as it first appears.
The regex will validate any string from 0 to 16 characters with only lowercase letters in the range a - z. The test method will return true if the input value match the regex and false otherwise. So any test which fails and return false will make the validate function return false.
Next is how to validate a username which contains at least 8 letters and at most 16 letters. Now the username may be both in upperacse and lowercase
1 function validate(form) { 2 // Regular expression for username 3 var rgx = /^[a-z]{8,16}$/i; 4 if(!rgx.test(form.elements.username.value)) 5 return false; 6 return true; 7 }
Notice the 'i' at the end of the regex. This means that case of the letters are ignored.
To allow for both letters and digits we can write
1 function validate(form) { 2 // Regular expression for username 3 var rgx = /^[a-z0-9]{8,16}$/i; 4 if(!rgx.test(form.elements.username.value)) 5 return false; 6 return true; 7 }
To accomodate for any leading and trailing spaces which we most likely would just like to ignore
1 function validate(form) { 2 // Regular expression for username 3 var rgx = /^\s*[a-z0-9]{8,16}\s*$/i; 4 if(!rgx.test(form.elements.username.value)) 5 return false; 6 return true; 7 }
Now even though this will validate with spaces before and after the username the spaces are still send to the server. You can either trim the username value before sending it or use your favorite server side language for adiitional checking.
| « Part 1 | Part 3 » |

Really helpfull... :) Thnks....