PDA

View Full Version : RegEx form verification



George Lucas
Nov 28th, 2009, 01:00 AM
i'm trying to build a html form and have a javascript file do RegEx checks on the values once it is submitted. i need some help getting started. is my current javascript correct in checking if there is a value there? eventually, i want it to make sure there are at least 2 alpha characters and no more than 20 in the firstname box.


html form

<form action="" onsubmit="return fistnameCheck()">
<fieldset>
<legend>Personal Information</legend>
Firstname*: <input type="text" name="firstname"/><br/>
Lastname*: <input type="text" name="lastname"/><br/>
<input type="reset" />
<input type="submit" />
</fieldset>
</form>



Javascript

function firstnameCheck() {
var error = "";
if (firstname == "") {
error = "You didn't enter a username.\n";
return window.confirm(error);
}

Old Pedant
Nov 28th, 2009, 04:38 AM
What regex???

And why are you using confirm??? If the user says "OK" to the confirm, then the form would submit even with the missing name.

I'd do it like this:


<script type="text/javascript">
function checkName( fld, show )
{
var nameRE = /[a-z]{2,20}/i ;
var val = fld.value.replace(/^\s+/,"").replace(/\s+$/,"");
fld.value = val; // replace after trimming spaces from ends
if ( nameRE.test(val) ) return "";
return "\nYou must supply a " + show + " with 2 through 20 letters."
}

function validateForm( form )
{
var oops = "";
oops += checkName( form.firstname, "first name");
oops += checkName( form.lastname, "last name");
// ... similar code for other fields ...

if ( oops == "" ) return true;
alert( "You must correct these errors:" + oops );
return false;
}
</script>
...
<form action="" onsubmit="return validateForm(this);">
<fieldset>
<legend>Personal Information</legend>
Firstname*: <input type="text" name="firstname"/><br/>
Lastname*: <input type="text" name="lastname"/><br/>
<input type="reset" />
<input type="submit" />
</fieldset>
</form>