Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking for Whitespace

Status
Not open for further replies.

GavW

Programmer
Jan 13, 2006
58
GB
Hey all.

I would like to know how to write form validation which will not allow whitespace to be included in a text box and return an error if the user attempts to submit the form whilst there is a space in the text box.

I am pretty new to javascript and cant seem to find sample code that will do this.

Thanks in advance
 
here's a simple function using a regular expression:
Code:
function has_whitespace(str) {
  return /\s/.test(str);
}
you can call it from your form validation:
Code:
function validate(form) {
  if (has_whitespace(form.myfield.value)) {
    alert('whitespace not allowed');
    return false;
  }
}
be sure to return false upon error in your validation function, and also have your form's onsubmit handler expect a return value to stop submission when false.
Code:
<form onsubmit='return validate(this);'>
 <input name='myfield' />
 <input type='submit' />
</form>

-jeff
lost: one sig, last seen here.
 
thanks a lot mate. Works perfect.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top