Check word length not working - javascript

HTML
<form name="f1" action="feedback1.php" method="Post" onSubmit="return isDataFilled();" >
<table border="0" align="center" width="500px" style="max-width: 500px;" cellspacing="3" cellpadding="5" align="center">
<tr align="left">
<td width="25%">
Enter your subject </td>
<td width="75%"><input type="text" name="subject" size="30" value="Your subject" onClick="if(this.value=='Your subject'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='Your subject'}; this.style.backgroundColor='white'"/></td>
</tr>
<tr align="left">
<td>
Enter your email<span style="color:#FF0000">*</span> </td>
<td>
<input type="text" name="email" size="30" value="example#mail.com" onClick="if(this.value=='example#mail.com'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='example#mail.com'}; this.style.backgroundColor='white'"/> </td>
</tr>
<tr align="left">
<td colspan="2">
Enter your message here<span style="color:#FF0000">*</span>: </td>
</tr>
<tr align="left">
<td colspan="2">
<textarea rows="10" cols="50" name="message" title="Your message goes here" onClick= "if(this.value=='Your message goes here'){this.value=''}; this.style.backgroundColor='#CCFF99'" onBlur="if(this.value==''){this.value='Your message goes here'}; this.style.backgroundColor='white'" >Your message goes here</textarea> </td>
</tr>
<tr>
<td colspan="" align="right">
<input type="submit" value="Send" name="b1" title="Send your message"/>
</td>
<td align="center">
<input type="reset" value="Reset" name="reset" title="Removes your form data and fill it again"/> </td>
</tr>
</table>
</form
JavaScript
function isDataFilled()
{
if(document.forms['f1']['email'].value=='example#mail.com')
{
alert("No email address in email field!");
return false;
}
if(document.forms['f1']['message'].value=='Your message goes here')
{
alert("No message in message field!");
return false;
}
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
}
function isEmailCorrect(f_email)
{
var x=f_email;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function check_word_length(text, over_size)
{
var word=0;
var message=text;
for(i=0;i<message.length;i++)
{
if(message.charAt(i)==" ")
{
word=0;
}
else
{
word++;
if(word>=over_size)
{
alert("Too long text entered");
return false;
}
}
}
}
The function check_word_length(text, over_size) is not working. I'm confused because I think my code is alright.

At the end of your isDataFilled:
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
The return keyword immediately exits the current function; so the second return in that code will never be reached.

When you return a value in a function, it ends that function. So what is after that will not be called. So in this part:
return isEmailCorrect(document.forms["f1"]["email"].value);
return check_word_length(document.forms['f1']['message'].value, 20);
... the function will stops after isEmailCorrect call.
Plus, stop copy/paste codes from web and start try your own codes to know what you're doing.

I believe the issue is being caused by the fact that isDataFilled returns whatever isEmailCorrect() returns. Execution in the function stops there, so it never calls the last function

Related

Pop-up is showing when i clear the text area . Want to show only for numbers

I am checking the form validation where the text area can't contain any numbers. But when I delete any text from the text area(when it is empty) the pop-up is showing again. I want to show the pop-up only for numbers.
function validate() {
var re = /^[A-Za-z]+$/;
if (re.test(document.getElementById('student_name').value)) {
return true;
} else {
alert('Numbers are not allowed.');
}
var element = document.getElementById('student_name');
element.value = element.value.replace(/[^a-zA-Z]+/, "");
}
<body>
<form action="" method="POST">
<tr>
<td width="40%" colspan="2">Name of the student<br>
</td>
<td width="60%" colspan="2">
<p align="left"><input type="text" name="Student_Name" size="20" autocomplete="off" id="student_name" oninput="validate()">
</p>
</td>
</tr>
</form>
</body>
You need to change your regex from /^[A-Za-z]+$/ to /^[A-Za-z]*$/.
Notice the difference between the + and * character,
+ matches one or more characters, so won't match an empty string.
Whereas * matches zero or more characters, so will match an empty string.
function validate() {
var re = /^[A-Za-z]*$/;
if (re.test(document.getElementById('student_name').value)) {
return true;
} else {
alert('Numbers are not allowed.');
}
var element = document.getElementById('student_name');
element.value = element.value.replace(/^[A-Za-z]*$/, "");
}
<body>
<form action="" method="POST">
<tr>
<td width="40%" colspan="2">Name of the student<br>
</td>
<td width="60%" colspan="2">
<p align="left"><input type="text" name="Student_Name" size="20" autocomplete="off" id="student_name" oninput="validate()">
</p>
</td>
</tr>
</form>
</body>
Something like this will work? I'm sure there's a better option, though.
function validate() {
var re = /^[A-Za-z]+$/;
if (re.test(document.getElementById('student_name').value) || document.getElementById('student_name').value === "" ) {
return true;
} else {
alert('Numbers are not allowed.');
}
var element = document.getElementById('student_name');
element.value = element.value.replace(/[^a-zA-Z]+/, "");
}
<body>
<form action="" method="POST">
<tr>
<td width="40%" colspan="2">Name of the student<br>
</td>
<td width="60%" colspan="2">
<p align="left"><input type="text" name="Student_Name" size="20" autocomplete="off" id="student_name" oninput="validate()">
</p>
</td>
</tr>
</form>
</body>
change the digits regex pattern to match on digits instead
change the if statement according to the regex
evaluate the cleanup with the same regex
full code:
function validate()
{
var re = /\d/;
if(!re.test(document.getElementById('student_name').value))
{
return true;
}
else
{
alert('Numbers are not allowed.');
}
var element=document.getElementById('student_name');
element.value=element.value.replace(re,"");
}
<body>
<form action="" method="POST">
<tr>
<td width="40%" colspan="2">Name of the student<br>
</td>
<td width="60%" colspan="2">
<p align="left"><input type="text" name="Student_Name" size="20" autocomplete="off" id="student_name" oninput="validate()">
</p>
</td>
</tr>
</form>
</body>

javascript Validation Help a total newbie

I Cannot get the javascript to work! I need the Password and Re-Type Password fields, validate that both have values and that the user has entered the same password in both fields (i.e. password match) validate the password field must be more than 8 characters.I dont want to use the alert function instead, highlight the uncompleted fields with red background and a text message next to each uncompleted field (in red color) with the error message.
I have spent 3 days doing this!! any help appreciated.`
function validate() {
var fn =
document.getElementById("FName");
if (fn.value == "") {
{
document.getElementById("FName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var sn =
document.getElementById("SName");
if (sn.value == "") {
document.getElementById("SName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var un =
document.getElementById("UName");
if (un.value == "") {
document.getElementById("UName").style.borderColor = "red";
return false;
}
return true;
}
function checkPass() {
var pass = document.getElementById('pass');
var c_pass = document.getElementById(' c_pass')
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value == c_pass.value) {
c_pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
c_pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
return true;
}
}
<body>
<form action="Linkpage.html" id="myForm" method="post" name="myForm" onsubmit="return(validate())">
</form>
<br>
<table>
<tr>
<td align="center" colspan="2"><span style="font-size:50px; color:blue;">Registration form</span>
</td>
</tr>
<tr>
<td align="center" colspan="2">Welcome to our website
<br>please fill in <span style=" color:red;">all</span>
<b><ins>fields</ins></b>
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input autofocus="" id="FName" placeholder="Enter First name " type="text">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input id="SName" placeholder="Enter Last name " type="text">
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input id="UName" placeholder="Enter username " type "text">
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input id="Age" placeholder="Enter age" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="pass" placeholder="Enter password " type="password">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm password" id="c_pass" placeholder="Re-type your password " type="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
</td>
</tr>
<tr>
<td rowspan="2">Gender</td>
<td>
<input name="mGender" type="radio" value="Male">Male</td>
</tr>
<tr>
<td>
<input name="fGender" type="radio" value="Female">Female</td>
</tr>
<tr>
<td>Available</td>
<td>
<input id="checkbox" type="checkbox">
</td>
</tr>
<tr>
<td>Course</td>
<td>
<select>
<option value="Mobile App">
Mobile App
</option>
<option value="Cloud">
Cloud
</option>
<option value="Software Development">
Software Development
</option>
</select>
</td>
</tr>
<tr>
<td class="Comments">Comments</td>
<td>
<br>
<textarea cols="30" name="Comments" placeholder="Type your comments here." rows="6"></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4" align="center">
<input name="submit" onclick="return validate()" type="submit" value="Register" align="center" />
</td>
</tr>
</table>
</body>
A couple of things here...
Get rid of the table, tr and td. You open a form and then you close it. Add all of your input fields in the form.
Then don't add three functions all called validate. Which one do you suppose is going to be called?
Rather change them to
function validateFname()
function validateSname()
function validateUname()
then
Use === and !=== instead of == and !=.
I think when you start clearing up your JavaScript and your HTML, things will start to make more sense.
Did you try to debug your code using Chrome's debugger or similar?
Each time you write the validate() function, you're overwriting the previous instance of it.
I recommend instead of using the same function name 3 times, write 2 different functions - matches() and required(), each with a different purpose.
matches(field1, field2){
return field1 == field2;
}
required(field){
return field != false;
}
Then you can pass into those functions the various fields you're validating.
There are a lot of bugs in your code and this is normal as a beginner its great to see you trying. So what I have done is took a look at your javascript. I am not going to re-write you whole script but I have commented out the part you should take a look at and try and comment one part at a time to see where you problem is. But I did get your match password working for you by commenting out your other stuff. Just try this for now. Then remove comments line by line until it stops working again. This will tell you how to find the other error's in your script.
<script>
function checkPass(){
var passValue = document.getElementById('pass').value;
var c_passValue = document.getElementById('c_pass').value;
var c_passID = document.getElementById('c_pass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(passValue == c_passValue) {
c_passID.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!";
} else {
c_passID.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
</script>
Okay so the issue was that you were attempting to change the color of the value of the c_pass and not the id itself. I renamed your variables to help you understand why it was breaking. Again this is only for the checkPass function. If you comment out all the other stuff and just use this script for now this will help you isolate the checkPass function and see that it works. I hope this helps.

the onblur and onsubmit function are not working could someone please help me out here

i am working on project using php,html,javascript. i am using on blur and onsubmit both the functions to provide dynamic kind of feel for errors. the following logic is working in every file except for this one .
The form functions like onsubmit and onblur are not working , i used an alert also to check but its not being called could someone please check and tell me where i am going wrong
<script language="Javascript">
//the flags are used to check if all the fields are filled and none is empty
var flag1;
var flag2;
var flag3;
function test(){
alert("fn called");
return true;
}
function fun1()
{
var donated_date=document.forms["myform"]["donated_date"];
if(donated_date==null||donated_date=="")
{
document.getElementById('ddate').innerHTML = "Choose the date of your last donation " ;
document.getElementById('ddate').style.display = "block" ;
flag1=false;
return false;
}
document.getElementById('ddate').style.display = "none" ;
flag1=true;
return true;
}
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
function fun3()
{
var hospital_name=document.forms["myform"]["hospital_name"];
if(hospital_name==null||hospital_name==""||!isNaN(hospital_name))
{
document.getElementById('hname').innerHTML = "Mention the Hospital Name where you last donated " ;
document.getElementById('hname').style.display = "block" ;
flag3=false;
return false;
}
document.getElementById('hname').style.display = "none" ;
flag3=true;
return true;
}
function validate()
{
alert("hello");
}
</script>
<form name="myform" method="post" action="o.php" onsubmit="return validate()">
<table width="94%" cellpadding="3px" class=" lastDonatedblood_table" cellspacing="0" style="border: 1px solid #CCCCCC;margin: -18px 0 14px 6px;width: 98.5%;">
<tr>
<td style="text-align:left;">Donated Date:</td>
<td style="text-align:left;">
<input type="text" name="donated_date" id="donated_date" onblur="return test();" style="width:300px;"/>
<div id="ddate"></div>
</td>
</tr>
<tr>
<td style="text-align:left;">Location:</td>
<td style="text-align:left;"><textarea name="location" id="location" onblur="return fun2();" style="width:300px;"></textarea></td>
</tr>
<center></center>
<tr>
<td style="text-align:left;">Hospital Name:</td>
<td style="text-align:left;"><input type="text" name="hospital_name" id="hospital_name" onblur="return fun3();" style="width:300px;"/></td>
</tr>
<center><div id="hname"></div></center>
<tr>
<td style="text-align:left;">Type of Donation:</td>
<td style="text-align:left;">
<select title="" name="donationtype" id="donationtype" style="width:317px;">
<option value="blood">Blood</option>
<option value="platelets">Platelets</option>
</select>
</td>
</tr>
<tr >
<td colspan="2">
<input name="submit" id="submit" value="ADD" type="submit" style="margin-top:5px; margin-left:185px; font-size:14px; width:100px;">
</td>
</tr>
</table>
</form>
you are missing closing curly bracket (function close) for fun2(),
function fun2()
{
var location=document.forms["myform"]["location"];
if(location==null||location==""||!isNaN(location))
{
document.getElementById('loc').innerHTML = "Mention the location of your last donation " ;
document.getElementById('loc').style.display = "block" ;
flag2=false;
return false;
}
document.getElementById('loc').style.display = "none" ;
flag2=true;
return true;
} <-- added closing curly bracket here
Check in console and you will get the error

Uncaught Reference Error: validateform is not definded

The code is very simple. But this is the first thing off this kind that I am doing, and I simply do not understand what it is that I am doing wrong.
Also this is the raw code straight from OCR.
This is GCSE computing coursework. I don't have to fix it, but I don't know how I'm supposed to test the stuff I'm going to add without the base code working.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm(document) {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById(‘name’).style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById(‘subject’).style.color = "red";
result = false;
}
if (msg == "") {
return result;
} {
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td id="subject">Subject</td>
<td>
<input type="text" name="subject" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onclick= return "validateForm()"; />
</td>
<td>
<input type="reset" name="Reset" value="Reset" />
</td>
</tr>
</table>
</form>
</body>
Your code has couple of syntax errors. I have removed that.
here is the fiddle link
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td id="subject">Subject</td>
<td>
<input type="text" name="subject" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onclick= " return validateForm();" /><!--js function inside quotes-->
</td>
<td>
<input type="reset" name="Reset" value="Reset" />
</td>
</tr>
</table>
</form>
<script>
//function had illegal parameter
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
// document.getElementById(‘name’).style.color = "red";--->Id should be in quotes
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
// document.getElementById(‘subject’).style.color = "red";--->Id should be in quotes
result = false;
}
if (msg == "") {
return result;
} {
alert(msg);
return result;
}
}
</script>

how to make the validation of my web form just like yahoo registration page?

i am able to display an alert msg when my form fields are empty but i want to display a red colored msg in front of empty field just like in yahoo registration form i dont know how to do this can any one explain to understand it
function validate_form ( )
{
valid = true;
if ( document.form.login.value == "" )
{
valid = false;
document.getElementById("LoginError").visible=false;
}
else
{
document.getElementById("LoginError").visible=false;
}
if(document.form.password.value == "" )
{
valid = false;
document.getElementById("PasswordError").visible=false;
}
else
{
document.getElementById("PasswordError").visible=false;
}
return valid;
}
//-->
</script>
<form name="form" method="post" action="UserLogin" onSubmit="return validate_form();">
<table width="592" height="127" border="0">
<tr>
<td width="46" height="29"> </td>
<td colspan="3"><%! private Boolean bRecord = false;
private Boolean bLogin = false;
%>
<% if(request.getAttribute("signup") != null)
bRecord =(Boolean)request.getAttribute("signup");
else
bRecord = false;
if(request.getAttribute("invalidlogin") != null)
bLogin =(Boolean)request.getAttribute("invalidlogin");
else
bLogin = false;
if(bRecord == true )
{%>
<font color="#336600"><b>You are Successfully Signed Up</b></font>
<%
request.removeAttribute("signup");
}//end if
if(bLogin == true )
{%>
<font color="#FF0000"><b>Invalid Login or Password</b></font>
<%
request.removeAttribute("invalidlogin");
}//end if
%></td>
</tr>
<tr>
<td> </td>
<td width="135"><div class="style1">LOGIN: </div></td>
<td width="146"><input type="text" name="login"></td>
<td width="247">*<span id="LoginError" visible="false" style="color: Red;">Enter login</span>
</td>
</tr>
<tr>
<td> </td>
<td><div class="style1">PASSWORD: </div></td>
<td><input name="password" type="password" id="password"></td>
<td>*<span id="PasswordError" visible="false" style="color: Red;">enter Password</span></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td align="right"><input name="Submit" type="image" class="bgtop" value="SIGN IN" src="images/btn_s.JPG" border="0" >
</td>
<td> </td>
</tr>
</table>
</form>
regards
You can simply add a non-visible span in front of the field
<span id="spanUsernameRequired" style="visibility: hidden; color: Red;">
This information is required</span>
<input id="username" type="text" />
Submit
, and then make it visible when the field is empty
function validate_form()
{
if (document.getElementById("username").value == "")
{
document.getElementById("spanUsernameRequired").style.visibility = 'visible';
return false;
}
else
document.getElementById("spanUsernameRequired").style.visibility = 'hidden';
return true;
}

Categories