I’ve working on a little form field character filter. The following script alters the background of every form field that matches the regular expression.
In reality, I need it the regular expression to do almost exactly the opposite.
The requirements are as follows…
Valid characters
A-Z
a-z
0-9
#
.
?
*
– (I know this one is not in the current reg exp)
s
Any field containing characters other than those listed under valid characters is incorrect and should have it’s background color changed.
Currently the script changes fields were the valid characters exist. I did this with the intention of just trying to make the regular expression match the inverse of the valid characters. I’ve been toying with this for a good four hours now (it now accepts spaces!) and I’m hoping someone with a little regular expression know how might be able to shed some light on the problem.
<html>
<head>
<SCRIPT language=”javascript”>
function checkFields(){
var pattern = new RegExp(“(s{0,}([A-Za-z0-9*?.#]+)s{0,})+”);
var form = document.forms[0];
var focusField = null;
for(var i = 0; i < form.length; i++){
var element = form.elements[i];
if(element.type == “text”){
if(element.value.search(pattern) != -1){
alert(“match on ” + i);
if(focusField == null) focusField = element;
element.style.background = “#D06868”;
}
else {
element.style.background = “”;
}
}
}
if(focusField != null) focusField.focus();
}
</SCRIPT>
</head>
<body>
<form>
<input type=”text” name=”blah”><br/>
<input type=”text” name=”blah1″><br/>
<input type=”text” name=”blah2″><br/>
<input type=”text” name=”blah3″><br/>
<button onclick=”checkFields()”>check</button>
</form>
</body>
</html>
Tim