Upload
sunil-soni
View
225
Download
0
Embed Size (px)
Citation preview
8/4/2019 Javascript Validation (Commonly Used)
1/20
Page 1
Document
VersionModification Comments
Modified
By
Reviewed
ByDate Comments
Draft 1.0 Created the document Sunil Soni - 11-09-2011
Contents
1. Introduction ......................................................................................................................................... 3
It is often a good idea to put your common JavaScript validation functions into a common file, so you
can include the file from all pages which need the form validation............................................................ 3
2. Date Validation .................................................................................................................................... 3
2.1. FromDate toDate ......................................................................................................................... 3
2.2. IsDate 1: ....................................................................................................................................... 4
2.3. Aalternative 2: ............................................................................................................................. 5
2.4. futureDateValidation :date format is DD/MM/YYYY .................................................................. 6
3. Email Validaton: ................................................................................................................................ 10
3.1. JavaScript Code1 ....................................................................................................................... 10
8/4/2019 Javascript Validation (Commonly Used)
2/20
Page 2
3.2. JavaScript Code 2 ....................................................................................................................... 11
4. Radio Button Validation .................................................................................................................... 12
4.1. getCheckedValue(): ................................................................................................................... 12
4.2. setCheckedValue():.................................................................................................................... 13
4.3. isCheckedRadio: ........................................................................................................................ 13
5. Checking for all Numbers: ................................................................................................................. 14
6. Checking for all Letters: ..................................................................................................................... 15
7. Checking for all Numbers and Letters: .............................................................................................. 16
8. Restricting the Length: ...................................................................................................................... 16
Example: ................................................................................................................................................ 16
9. Remove Special Characters from string: ........................................................................................... 17
10. Username Validation: .................................................................................................................... 17
10.1. ....................................................................................................................................................... 17
11. Password Validation: .................................................................................................................... 18
12. Phone Number Validation: ........................................................................................................... 19
12.1. Validation 1: .......................................................................................................................... 19
12.2. Validation 2: .......................................................................................................................... 19
13. Dropdown Validation: .................................................................................................................. 20
14. Links: .............................................................................................................................................. 20
Dynamic JavaScript Form Validation ......................................................................................................... 20
8/4/2019 Javascript Validation (Commonly Used)
3/20
Page 3
1.IntroductionIt is often a good idea to put your common JavaScript validation functions into a
common file, so you can include the file from all pages which need the formvalidation.
2.Date Validation2.1. FromDate toDate
This is the code for date comparison fromDate should be less than toDate
var objFromDate = document.getElementById("fromdate").value;
var objToDate = document.getElementById("todate").value;
var FromDate = new Date(objFromDate);
var ToDate = new Date(objToDate);
var valCurDate = new Date();
val CurDate = valCurDate.getMonth()+1 + "/" + valCurDate.getDate() + "/" + valCurDate.getYear();
var CurDate = new Date(valCurDate);
if(FromDate > ToDate)
{
alert(fromname + " should be less than " + toname);
return false;
}
else if(FromDate > CurDate)
{
alert("From date should be less than current date");
return false;
}
else if(ToDate > CurDate)
8/4/2019 Javascript Validation (Commonly Used)
4/20
Page 4
{
alert("To date should be less than current date");
return false;
}
2.2. IsDate 1:function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strMonth=dtStr.substring(0,pos1)
var strDay=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1)
strMonth=strMonth.substring(1)
for (var i = 1; i 1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : mm/dd/yyyy")
return false
}
8/4/2019 Javascript Validation (Commonly Used)
5/20
Page 5
if (strMonth.length daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || yearmaxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and
"+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr,
dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}
2.3. Aalternative 2:function isDate(value){
var dateRegEx = newRegExp(/^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-
8/4/2019 Javascript Validation (Commonly Used)
6/20
Page 6
)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
if (dateRegEx.test(value)){
return true;}return false;
}
2.4. futureDateValidation :date format is DD/MM/YYYY
future date validation
function futureDateValidation(){
var dtCh="/";
// Get today's date and time...
var todaysDateTime = new Date();
// Parse off the time...
var monthValue = todaysDateTime.getMonth() + 1;
var dayValue = todaysDateTime.getDate();
var yearValue = todaysDateTime.getFullYear();
var todaysDate = new Date(Date.parse(monthValue + '/' + dayValue + '/' + yearValue));
// Create the FromDate to validate...
var enqiryFromDate = document.getElementById('fromDate').value; // this is how the date
looks like: ex 05/19/2008
var pos1=enqiryFromDate.indexOf(dtCh)
8/4/2019 Javascript Validation (Commonly Used)
7/20
Page 7
var pos2=enqiryFromDate.indexOf(dtCh,pos1+1)
var strDay=enqiryFromDate.substring(0,pos1)
var strMonth=enqiryFromDate.substring(pos1+1,pos2)
var strYear=enqiryFromDate.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i 1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
var enqiryFromDateObj = new Date(Date.parse(month + '/' + day + '/' + year));
// Create the Todate to validate...
var enqiryToDate = document.getElementById('toDate').value;
var position1=enqiryToDate.indexOf(dtCh)
var position2=enqiryToDate.indexOf(dtCh,position1+1)
var stringDay=enqiryToDate.substring(0,position1)
var stringMonth=enqiryToDate.substring(position1+1,position2)
var stringYear=enqiryToDate.substring(position2+1)
//strYr=strYear
if (stringDay.charAt(0)=="0" && stringDay.length>1) stringDay=stringDay.substring(1)
8/4/2019 Javascript Validation (Commonly Used)
8/20
Page 8
if (stringMonth.charAt(0)=="0" && stringMonth.length>1)
stringMonth=stringMonth.substring(1)
for (var i = 1; i 1)
stringYear=stringYear.substring(1)
}
toMonth=parseInt(stringMonth)
toDay=parseInt(stringDay)
toYear=parseInt(stringYear)
var enqiryToDateObj = new Date(Date.parse(toMonth + '/' + toDay + '/' + toYear));
if ( enqiryFromDateObj > todaysDate )
{
alert("Invalid date range!\nPlease choose a date that is not earlier than today!")
document.getElementById('fromDate').style.border = "2px solid red";
document.getElementById('fromDate').focus();
return false;
}
else
{
if(enqiryToDateObj > todaysDate){
alert("Invalid date range!\nPlease choose a date that is not earlier than
today!")
document.getElementById('toDate').style.border = "2px solid red";
document.getElementById('toDate').focus();
8/4/2019 Javascript Validation (Commonly Used)
9/20
Page 9
return false;
}
else{
//alert('OK');
return true;
}
}
}
8/4/2019 Javascript Validation (Commonly Used)
10/20
Page 10
3.Email Validaton:Every email is made up for 5 parts:
1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores2. The at symbol @3. A combination of letters, numbers, hyphens, and/or periods4. A period5. The top level domain (com, net, org, us, gov, ...)
Valid Examples:
[email protected] [email protected] [email protected]
Invalid Examples:
@deleted.net - no characters before the @ [email protected] - invalid character ! shoes@need_shining.com - underscores are not allowed in the domain name
3.1. JavaScript Code1function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){return true;
}else{alert(helperMsg);elem.focus();return false;
}}
Example:
function emailValidator(elem, helperMsg){var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;if(elem.value.match(emailExp)){
return true;}else{
alert(helperMsg);elem.focus();
8/4/2019 Javascript Validation (Commonly Used)
11/20
Page 11
return false;}
}
Email:
3.2. JavaScript Code 2
function trim(s){return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {var error="";var tfld = trim(fld.value); // value of
field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;var illegalChars= /[\(\)\\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {fld.style.background = 'Yellow';error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test emailfor illegal characters
fld.style.background = 'Yellow';error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {fld.style.background = 'Yellow';error = "The email address contains illegal characters.\n";
} else {fld.style.background = 'White';
}return error;
}
8/4/2019 Javascript Validation (Commonly Used)
12/20
Page 12
4.Radio Button ValidationTo make sure that a radio button has been chosen from a selection, we run through the array ofradio buttons and count the number that have been checked. Rather than sending the wholeradio object to a subfunction, which can be problematic (because the radio object has noproperty indicating which value has been chosen), we pre-process the radio form element in afor loop and send that result to a subfunction for evaluation.
4.1. getCheckedValue():return the value of the radio button that is checked return an empty string if none are checked, or
there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
8/4/2019 Javascript Validation (Commonly Used)
13/20
Page 13
4.2.
setCheckedValue():set the radio button with the given value as being checked , do nothing if there are no radio buttons
if the given value does not exist, all the radio buttons are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
4.3. isCheckedRadio:function isCheckedRadio(){
var isSelected=false;
8/4/2019 Javascript Validation (Commonly Used)
14/20
Page 14
if( document.getElementById('tranType1').checked){
isSelected=true;
}
if( document.getElementById('tranType2').checked){
isSelected=true;
}
return isSelected;
}
5.Checking for all Numbers:If someone is entering a credit card, phone number, zip code, similar
information you want to be able to ensure that the input is all numbers. The
quickest way to check if an input's string value is all numbers is to use a
regular expression /^[0-9]+$/ that will only match if the string is all numbers
and is at least one character long.
function isNumeric(elem, helperMsg){var numericExpression = /^[0-9]+$/;if(elem.value.match(numericExpression)){
return true;}else{
alert(helperMsg);elem.focus();return false;
}}
Example:
function isNumeric(elem, helperMsg){var numericExpression = /^[0-9]+$/;if(elem.value.match(numericExpression)){
8/4/2019 Javascript Validation (Commonly Used)
15/20
8/4/2019 Javascript Validation (Commonly Used)
16/20
Page 16
}}Letters Only:
7.Checking for all Numbers and Letters:
By combining both the isAlphabetand isNumeric functions into one we can check to see if a text input
contains only letters and numbers.
function isAlphanumeric(elem, helperMsg){var alphaExp = /^[0-9a-zA-Z]+$/;if(elem.value.match(alphaExp)){
return true;}else{
alert(helperMsg);elem.focus();return false;
}}
8.Restricting the Length:Being able to restrict the number of characters a user can enter into a field is one of the best ways to
prevent bad data. For example, if you know that the zip code field should only be 5 numbers you know
that 2 numbers is not sufficient.
function lengthRestriction(elem, min, max){var uInput = elem.value;if(uInput.length >= min && uInput.length
8/4/2019 Javascript Validation (Commonly Used)
17/20
Page 17
function lengthRestriction(elem, min, max){var uInput = elem.value;if(uInput.length >= min && uInput.length
8/4/2019 Javascript Validation (Commonly Used)
18/20
8/4/2019 Javascript Validation (Commonly Used)
19/20
Page 19
12. Phone Number Validation:To validate a phone number, first we want to clear out any spacer characters, such asparentheses, dashes, spaces, and dots. We can do this with a regular expression and thereplace() method, replacing anything that matches our regular expression with a null string.
Having done that, we look at what we have left with the isNaN() function (which checks to seeif a given input is Not A Number), to test if it's an integer or not. If it contains anything otherthan digits, we reject it.
12.1. Validation 1:var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');//strip out acceptable non-numeric characters
if (isNaN(parseInt(stripped))) {error = "The phone number contains illegal characters.";
}
Then we count the length of the number. It should have exactly ten digitsany more orless, and we reject it.
if (!(stripped.length == 10)) {error = "The phone number is the wrong length.Make sure you included an area code.\n";
}
12.2. Validation 2:function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. Make sure you included an area code.\n";
fld.style.background = 'Yellow';
}
return error
8/4/2019 Javascript Validation (Commonly Used)
20/20
13. Dropdown Validation:We want to make sure that the user has selected an option from our drop-down menu (and notthe first option, which isnt an option at all, but just a "Choose one" header). For this, we use the
select objects selectedIndex property, which returns the index of the selected option. If theindex is 0, we reject the input.
function checkDropdown(choice) {var error = "";if (choice == 0) {
error = "You didn't choose an optionfrom the drop-down list.\n";
}return error;}
14. Links:
Dynamic JavaScript Form Validation
http://sandbox.scriptiny.com/messages/messages.html
http://www.scriptiny.com/2008/04/dynamic-inline-javascript-form-validation/
http://sandbox.scriptiny.com/messages/messages.htmlhttp://sandbox.scriptiny.com/messages/messages.htmlhttp://www.scriptiny.com/2008/04/dynamic-inline-javascript-form-validation/http://www.scriptiny.com/2008/04/dynamic-inline-javascript-form-validation/http://www.scriptiny.com/2008/04/dynamic-inline-javascript-form-validation/http://sandbox.scriptiny.com/messages/messages.html