During web development, nearly always, we need to provide input validation on even simple web forms. And in the case of the web, JavaScript is the best option available for validating input client-side. Server-side validation has its own use and it should be there but restricting user at the beginning is always needed.
So, in this web development article, I am trying to present some requirements to limit the scope of the article, which are as follows:
- Only Numeric
Only numeric input should be allowed for some fields. So the user can't enter non-numeric characters in those particular fields. One step further, the user can't even copy & paste non-numeric input.
- Only Character
Limited to alphabetic character input only with an exception i.e. a space character that might be required even if we are entering only letters. Similarly, copy & paste must be restricted for other characters.
- Alphanumeric
Alphanumeric input allowed for certain fields but very restricted. Many of other or special characters shouldn't be allowed.
- Email validation
Validate against standard email format.
In order to apply these validations, we have a simple "Create User" form having the following fields:
- User Full Name: Only alphabetic characters and spaces.
- Username: Only alphabetic characters with dots (".") or dashes ("-").
- Password: Anything acceptable.
- Email: Standard Email format
- Mobile: Only numeric input
So, JavaScript functions are explained along with each field for understanding. Let's take each field one by one with its validation code.
First, a User Full Name field that will allow entering only alphabets and a space character. Alphabets can be upper or lower case letters. For example, my son's complete name will be "Muhammad Ahmad". So, the following field will take input accordingly.
<asp:TextBox ID="txtFullName" onkeypress="return ValidateLettersWithSpaceOnly(event);"
onPaste="return ValidateFullNamePaste(this);" MaxLength="50" runat="server">
</asp:TextBox>
The JavaScript function validating the input is:
function LettersWithSpaceOnly (evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode > 32 && (charCode < 65 || charCode > 90) &&
(charCode < 97 || charCode > 122)) {
return false;
}
return true;
}
function ValidateFullNamePaste (obj)
{
var totalCharacterCount = window.clipboardData.getData('Text');
var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
var strChar;
var FilteredChars = "";
for (i = 0; i < totalCharacterCount.length; i++) {
strChar = totalCharacterCount.charAt(i);
if (strValidChars.indexOf(strChar) != -1) {
FilteredChars = FilteredChars + strChar;
}
}
obj.value = FilteredChars;
return false;
}
Secondly, the Username/Login field will allow entering letter, dot (".") or dash ("-") characters.
<asp:TextBox ID="txtUsername"
onkeypress="return ValidateUsernameOnly(event);"
onPaste="return ValidateUsernamePaste(this);"
MaxLength="30" runat="server">
</asp:TextBox>
function ValidateUsernameOnly(evt)
{
evt = (evt) ? evt : event;
var characterCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (characterCode > 31 && (characterCode < 65 || characterCode > 90) && (characterCode < 45 || characterCode > 46) &&
(characterCode < 97 || characterCode > 122) && (characterCode < 48 || characterCode > 57)) {
return false;
}
return true;
}
function ValidateUsernamePaste(obj)
{
var totalCharacterCount = window.clipboardData.getData('Text');
var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
var strChar;
var FilteredChars = "";
for (i = 0; i < totalCharacterCount.length; i++) {
strChar = totalCharacterCount.charAt(i);
if (strValidChars.indexOf(strChar) != -1) {
FilteredChars = FilteredChars + strChar;
}
}
obj.value = FilteredChars;
return false;
}
For the Email field, a standard email validation is applied but it's triggered on form submission.
<asp:TextBox ID="txtEmail"
MaxLength="30" runat="server">
<asp:Button ID="btnSave" Text="Create User" runat="server"
OnClientClick="validateEmail(this);" />
function validateEmail(emailField)
{
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false) {
alert('Invalid Email Address');
return false;
}
return true;
}
And finally, numeric validation for a phone number field is as follows:
<asp:TextBox ID="txtPhone"
onkeypress="return ValidateNumberOnly(event);"
onPaste="return ValidateNumberPaste(this);"
MaxLength="10" runat="server">
</asp:TextBox>
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
function ValidateNumberPaste(obj)
{
var totalCharacterCount = window.clipboardData.getData('Text');
var strValidChars = "0123456789";
var strChar;
var FilteredChars = "";
for (i = 0; i < totalCharacterCount.length; i++) {
strChar = totalCharacterCount.charAt(i);
if (strValidChars.indexOf(strChar) != -1) {
FilteredChars = FilteredChars + strChar;
}
}
obj.value = FilteredChars;
return false;
}
Although this article uses ASP.NET controls as an example, this JavaScript code fully supports standard HTML input controls as well.