View Full Version : validating in JS- no spaces in a word
d-machine
06-13-2008, 12:29 PM
I want to check some form input, that it should be only one word without spaces and that it will be at least 6 characters.
I succeeded checking that length of the word, but didn't know what to do about the spaces.
my function:
// If it is at least 6 characters it attaches class="welldone" to the containing fieldset.
function checkUsernameForLength(whatYouTyped) {
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 5) {
fieldset.className = "welldone";
}
else {
fieldset.className = "";
}
}
Just replace the spaces using this method: http://www.tizag.com/javascriptT/javascript-string-replace.php
d-machine
06-14-2008, 05:06 AM
Just replace the spaces using this method: http://www.tizag.com/javascriptT/javascript-string-replace.php
hi thanks but i don't want to replace it, i want to write some condition which will check it
rangana
06-14-2008, 05:59 AM
Use indexOf() (http://www.w3schools.com/jsref/jsref_indexOf.asp).
if(!(txt.indexOf('')==-1))
{
alert('spaces is present');
}
Hope it helps.
coothead
06-14-2008, 06:36 AM
Hi there d-machine,
this will check for 6 or more letters...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
window.onload=function() {
document.forms[0][1].onclick=function() {
if(document.forms[0][0].value.match(/^[a-zA-Z]{6,}$/)){
alert('the input matches the requirement');
}
else {
alert('the input does not match the requirement');
}
}
}
</script>
</head>
<body>
<form action="#">
<div>
<input type="text">
<input type="button" value="check">
</div>
</form>
</body>
</html>
coothead
d-machine
06-14-2008, 07:32 PM
Thank you both !! :)
You are awesome I really appreciate your help.
coothead
06-14-2008, 07:57 PM
No problem, you're welcome. ;)
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.