About the author

Miron Abramson
Me
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

Prevent from the user to submit any 'not legal' input, using client side validation

We are all know that client validations are good way to validate input, of cource you must re validate in server side also, but the client side will save some wasted post backs. Usually, we validate each input separate (writing manually script, or a validator control). What if you have a rule that is for all inputs in the page, or in the site? for example, you want to prevent the user to submit any input that contains 'fuc*' , 'shi*' or what ever words that are not 'legal' for you, or input that is not valid for the ASP.NET such '<'or  '/>' ?

I wrote some JavaScript code, that validate all the TextBox and Textarea controls in the page, and prevent it to be submitted if one (or more) of the input/s is in your 'not legal words' list. What the script actualy does, is checking the values of all Textboxes in the page, and if one input value contains one of the 'bad' words that defined in the 'MachingWords' variable, it will pop an alert, and will cancel the submit.  Here we go:

 // List of 'bad' words.  Append here all the words you want from the user to submit as an input, seperates by '|' char.

var MachingWords = "<|/>|fuck|shit|ass";


function FormValidationController()
{
    this.IsValid = true;
    this._notValidValuesCollection = [];
    this._notValidValuesHash = new Array();
    this.AddNotValidValue = function(value){   
        if( !this._notValidValuesHash[value] ){
            this._notValidValuesHash[value] = 1;
            this._notValidValuesCollection.push(value);
        }
    }
    this.PopMessage = function() {
        var wordsList = '';
        for( var i = 0 ; i < this._notValidValuesCollection.length ; i++ ) {
            wordsList = wordsList.length < 1 ? "'" + this._notValidValuesCollection[i] + "'" : wordsList + ", '" + this._notValidValuesCollection[i] + "'";
        }
        var notValidMessage = "The input{0} {1} {2} not valid.";
        alert( String.Format(notValidMessage,(this._notValidValuesCollection.length > 1 ? "s" : ""),(wordsList),(this._notValidValuesCollection.length > 1 ? "are" : "is")) );
    }
    this.Validate = function(){
        this.IsValid = true;
        this._notValidValuesCollection = [];
        this._notValidValuesHash = new Array();
        var inputElementsCollection = document.getElementsByTagName("INPUT");
        if( inputElementsCollection ){
            for (var index=0; index<inputElementsCollection.length; index++) {
                var el=inputElementsCollection[index];
                if( el.type.toLowerCase() == 'text' )
                    this.ValidateInput(el);
            }
        }
        var textareaElementsCollection = document.getElementsByTagName("TEXTAREA");
        if( textareaElementsCollection ){
            for (var index=0; index<textareaElementsCollection.length; index++) {
                var el=textareaElementsCollection[index];
                this.ValidateInput(el);
            }
        }
    }
    this.ValidateInput = function (element) {
        if( element ){
            if( !this.IsValidString(element.value) ) {
                this.AddNotValidValue(element.value);
                if( this.IsValid ){
                    this.IsValid = false;
                    element.focus();
                    element.select();
                }
            }
        }
    }
}

FormValidationController.RegularExpression = new RegExp(MachingWords,"i","g");
// Validate the current input
FormValidationController.prototype.IsValidString = function(strInput)
{   
    if( !strInput || typeof( strInput ) == 'string' ){
          if( strInput.length < 1 )
            return true;
    }
    if( FormValidationController.RegularExpression.test ( strInput ) )
        return false;
    return true;
}
var c = new FormValidationController();

//
// String.Format implementation
//
String.Format = function(format,args){
    var result = format;
    for(var i = 1 ; i < arguments.length ; i++) {
        result = result.replace(new RegExp( '\\{' + (i-1) + '\\}', 'g' ),arguments[i]);
    }
    return result;
}

And the method that using it and excuting the validation:

 //
//  Excute the validation
//
function ValidatePage() {
    c.Validate();
    if( !c.IsValid ) {
           c.PopMessage();
           return false;
      }
    return true;
}

 The implementation is very simple. Add the script to your page, and add to  the OnLoad page event  the following line, and that's it.

ClientScript.RegisterOnSubmitStatement(this.GetType(), "ValidatePage", "return ValidatePage();");

Javascript file with the code available here: 

FormValidation.js (3.23 kb)

Currently rated 4.8 by 4 people

  • Currently 4.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | Client side
Posted by Miron on Saturday, May 17, 2008 9:53 AM
Permalink | Comments (2) | Post RSSRSS comment feed

Some basic but useful C# methods implemented in JavaScript

While I was working on a full Ajax interface based on pure ajax calls and not on any framework,  I implemented some basic and simple methods that we use all the time in the server code, and just not exist in javascript. It's not big deal, but since I wrote them, I use them all the time.

Even it is very simple, I decided to share it here. Hope it will save other coders few minutes:

Cache object:

//
//  Cach object implementation
//
var Cache = new function()
{
    var _cache = new Array();
    this.Insert = function ( key, value ){
        _cache[key] = value;
        }
    this.Get = function ( key ){
        return _cache[key];
        }
    this.Contains = function ( key ){
        if( !_cache[key] || _cache[key] == null ) return false;
        else return true;
        }
};

The use of the cache is as simple as it is in the server side, and it is realy useful to save some calls to the server:

 Cache.Insert("myKey","MyValue");
 if( Cache.Contains("myKey") ) alert( "Yeee the value of my key is in the cache:" + Cache.Get("myKey") );  

String.Format(string,params)  &  String.IsNullOrEmpty(string) :

//
// String.Format implementation
//
String.Format = function(format,args){
    var result = format;
    for(var i = 1 ; i < arguments.length ; i++) {
        result = result.replace(new RegExp( '\\{' + (i-1) + '\\}', 'g' ),arguments[i]);
    }
    return result;
}

//
// String.IsNullOrEmpty implementation
//
String.IsNullOrEmpty = function(value){
    if(value){
        if( typeof( value ) == 'string' ){
             if( value.length > 0 )
                return false;
        }
       if( value != null )
           return false;
    }
    return true;
}

Again, the use is the same as server side:

alert( String.Format("Hello {0}. Yes, hello {0} again. My name is {1}","world","Miron") );
if( String.IsNullOrEmpty('') ) alert('Empty string');

StartsWith(string suffix,bool ignoreCase)EndsWith(string suffix,bool ignoreCase)  and Trim() :

//
// string.StartWith implementation
//
String.prototype.StartsWith = function(prefix,ignoreCase) {
    if( !prefix ) return false;
    if( prefix.length > this.length ) return false;
    if( ignoreCase ) {
        if( ignoreCase == true ) {
            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
        }
    }
    return (this.substr(0, prefix.length) === prefix);
}

 //
// string.EndsWith implementation
//
String.prototype.EndsWith = function(suffix,ignoreCase) {
    if( !suffix ) return false;
    if( suffix.length > this.length ) return false;
    if( ignoreCase ) {
        if( ignoreCase == true ) {
            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
        }
    }
    return (this.substr(this.length - suffix.length) === suffix);
}

 //
// string.Trim implementation
//
String.prototype.Trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
}

The last three are working on an istance of a string:

var test = "Hello Words ";
test = test.Trim();
var end = test.EndsWith("ds",true);
var begin = test.BeginsWith("rr",false);

All the code can be downloaded here: 

Utils.js (1.94 kb)

Currently rated 4.8 by 8 people

  • Currently 4.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Client side
Posted by Miron on Sunday, May 04, 2008 4:43 PM
Permalink | Comments (3) | Post RSSRSS comment feed

Check all CheckBoxes in GridView in client side

'Lists' controls as GridView, DataList or Repeater sometimes have a column with CheckBoxes. It is very usefull to let the user 'Select all' or 'Un Select all'. One way to do it is to loop on the control in the code behind and check/un check the CheckBoxes, or faster way is to do it on the client side, using the same idea of my preview  post:

//
//  Select or unSelect checkboxes in grid view
//
function CheckAllCheckBoxes(aspxCheckBoxID, checkVal)
{
    var reg = new RegExp( aspxCheckBoxID + "$" );
    var pageElements = document.getElementsByTagName("*");
    for(i = 0; i < pageElements.length; i++) {
        elm = pageElements[i];
        if (elm.type == 'checkbox')
        {
            if (reg.test(elm.name))
            {  
                elm.checked = checkVal
            }
        }
    }
 }

Where 'aspxCheckBoxID' is the CheckBox server side name, and 'checkVal is value if to check all or uncheck all. So simple.

Happy coding 

Currently rated 4.8 by 5 people

  • Currently 4.8/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | Client side
Posted by Miron on Saturday, September 01, 2007 5:55 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Server side controls in client side

Long time ago, When I started to work with ASP.NET 2.0, I was very engry with MS because most of the Server-Side controls changed their names in the client side: 'imgbtnFind' in the code-behind became 'ctl00_cphMPContent_imgbtnFind' in the client side, etc... (as I remeber, it wasn't like this in ASP.NET 1.1) How the Fu-- we can write JavaScript code that works with those controls??? If the JS code is in the page,  we can use '<%= imgbtnFind.ClientID %>', but what if the JS code is in external .js file ?

'We have a problem Houston!'

I came up with the following function, and I can't write even single JS function without using it: 

//  Get element in the page ( the same as document.getElementById(), but can be use
//  for server-side controls that .NET change their names) 
function $getElement( elementID, elementIndex ){
    if( document.getElementById(elementID) )
        return document.getElementById(elementID);
    var reg = new RegExp(  elementID + "$" );
    var counter = 0;
    var pageElements = document.getElementsByTagName("*");
    for(i = 0; i < pageElements.length; i++) {
        elm = pageElements[i];
        if( elm.id ) {
            if ( reg.test(elm.id) ) {  
                if( typeof(elementIndex) == 'number' ) {
                    if( counter == elementIndex ) { return elm; }
                }else { return elm; }
                counter ++;
            }
        }
    }

Just place it in your javascript file that common to all your pages (as usualy web application have), and you can freely use $getElement(elementID) instead  of document.getElementById(elementID) - for client side controls and for server-side controls as well. The rendering process in the aspx page  concatenate all the parents containers names to the prefix of the control, So that function is checking for the suffix of the control name. The only  thing to take care is to don't have two controls that complete server name of one is the exact suffix of the other, Or if you must to, you can use the second parameter of the function to control duplicate names... So now, to use the server control 'imgbtnFind' in the client side, just use $getElement('imgbtnFind') ...

Happy coding ! 

Currently rated 4.4 by 5 people

  • Currently 4.4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | Client side
Posted by Miron on Thursday, August 30, 2007 11:53 PM
Permalink | Comments (1) | Post RSSRSS comment feed