Jump to content

Validating using RegExp on Form


sharon5467

Recommended Posts

HiI am trying to create the below form without much success. Please can anyone provide any tips or pointers of what I am doing wrong?<html><head><title>Untitled Document</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><script LANGUAGE="JavaScript" type="text/javascript"><!-- hide javascript codevar justValidating = truefunction validateForm(form) //validate assessment data { if (!validateStudentNumber(form.studentNum.value)) // student number valid? { form.studentNum.focus() return false }if (justValidating) // only show alert box if validating, and not submitting alert("Well Done: Your data is valid!") // all data validated return true }function validateStudentNumber(studentNum) { var myRegexp = /^[A-Z]{2}\d{7}/ if(myRegexp.test(/^[A-Z]{2}\d{7}/)) } alert("Please enter two letters before seven digits!") return false } return true }// end javascript hide --></SCRIPT></head><BODY BGCOLOR="white" TEXT="blue" onLoad="window.defaultStatus='JavaScript Assessment Frame'"><CENTER><H2>JavaScript Assessment</H2> <FORM NAME="assessForm" METHOD="post" ACTION="mailto:skinton11@yahoo.co.uk" onSubmit="justValidating=false; return validateForm(assessForm)"> Student Number: <INPUT NAME="studentNum" TYPE="text" SIZE="12" maxlength="9"> <INPUT TYPE="submit" VALUE="Submit"> <INPUT TYPE="button" VALUE="Validate" onClick="justValidating=true; validateForm(this.form)"> <INPUT TYPE="reset" VALUE="Reset"></FORM></body></html>Anyone have any suggestions??Many ThanksSharon :)

Link to comment
Share on other sites

Don't forget the '$' at the end of the regular expression, it's very important.Without it the string could 'end' with anything.You'll need to inspect the way you are calling the 'test' also, here's your fixes:

<script type="text/javascript"><!-- hide javascript codevar justValidating = truefunction validateForm(form) //validate assessment data{  if (!validateStudentNumber(form.studentNum.value)) // student number valid?  {  form.studentNum.focus()  return false  }  if (justValidating) // only show alert box if validating, and not submitting  alert("Well Done: Your data is valid!") // all data validatedreturn true}function validateStudentNumber(studentNum){  var myRegexp = /^[A-Z]{2}\d{7}$/   if(!myRegexp.test(studentNum))   {    alert("Please enter two letters(Caps Please) before seven digits!")    return false   }return true}// end javascript hide --></script>

Thanks,

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...