Some times I need to run RegEx Scripts on text boxes.
Here is a simple RegEx Sanity Checker for ASP.NET - You can download this from my SourceForge Page
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FieldOfSheep
{
[ToolboxData("<{0}:SanityChecker runat=server>{0}:SanityChecker >")]
public class SanityChecker : TextBox
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "SanityChecker.js", JScript.SanityChecker, true);
this.Attributes.Add("onkeyup", string.Format("return SanityChecker(event,'{0}');", this.ClientID));
}
}
}
And the JavaScript code for this is
function SanityChecker(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode > 93 && charCode < 112 || charCode > 46 && charCode < 91 || charCode > 185 && charCode < 223)
{
var rex = /^[^<>&\"\';]*$/;
var value = document.getElementById(element).value;
if(rex.test(str))
{
return true;
}
else
{
value = str.substring(0,value.length -1);
document.getElementById(element).value = value;
}
}
}
No comments:
Post a Comment