Sunday, 4 March 2012

Javascripte validation trick

How to have the status line update when the mouse goes over a link ?

onmouseover="window.status='Hi There!';return true"
onmouseout="window.status='';return true"

need to set the cursor at the end of text in textbox

function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.setSelectionRange(selectionStart, selectionEnd);
else if (input.createTextRange) {
var range = input.createTextRange();
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);;
function setCaretToEnd (input) {
setSelectionRange(input, input.value.length, input.value.length);

Detect special characters in text box. Or any character you subsitute for the special characters.

var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("The box has special characters. \nThese are not allowed.\n");
return false;

Remove special characters from a string.

Remove special characters from a string.

function clearText() {

function filterNum(str) {
re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");

Scan values in a field and if they are all letters then alert. The second block of code does the same but for numbers

//alert on finding all letters
var noalpha = /^[a-zA-Z]*$/;
if (noalpha.test(document.formname.fieldname.value)) {
alert("Please enter at least one number in the \"username\" field.");
return false;

//alert on finding all numbers
var nonums = /^[0-9]*$/;
if (nonums.test(document.formname.fieldname.value)) {
alert("Please enter at least one letter in the \"username\" field.");
return false;

Check drop down has been selected. Set drop down's value to Not_Selected for this to work.

if (document.formname.fieldname.value == 'Not_Selected')
alert("Please provide us with a selection.\n");
return false;
Post a Comment