Quantcast
Viewing latest article 5
Browse Latest Browse All 7

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 )
            returntrue;
    }
    if( FormValidationController.RegularExpression.test ( strInput ) )
        returnfalse;
    returntrue;
}
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();
           returnfalse;
      }
    returntrue;
}

 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)


Viewing latest article 5
Browse Latest Browse All 7

Trending Articles