alert is not working as expected! i don't know why...
I am trying to evaluate a form on client side. I have tried getElementsById, getElementsByName.
Where am i going wrong?
I am sure the flow of control goes through validate()
an alert statement immediately inside validate method is being displayed!
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" errorPage="Error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexof('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
</script>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName : <input type="text" name="uname" id="uname" value='${ param.uname}'placeholder="Enter Name" ><br/><br/>
Enter Email: <input type="email" name="email" id = "email" value='${param.email}'placeholder="Enter Email"><br/><br/>
Enter Password: <input type="password" name="pass" id = "pass" value='${param.pass}'placeholder="Enter password"><br/><br/>
Repeat Password: <input type="password" name="rpass" id = "rpass" value='${param.rpass}'placeholder="Repeat Password"/><br/>
<br/><br/>
<input type="submit"/>
</form>
<h4>${errorMsg}</h4>
</body>
</html>
Spelling of alret and indexOf !
getElementById is singular
submitOK="false" sets submitOK to true since a non-empty string is truthy. use submitOK=false
you did not return submitOK when you asked the question
function validate() {
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value.indexOf('#');
var pass = document.getElementById("pass").value;
var rpass = document.getElementById("rpass").value;
submitOK = true;
if (uname.length == 0) {
alert("Username cannot be empty")
submitOK = false;
}
if (email == -1) {
alert("Not a valid email");
submitOK = false;
}
if (pass.length === 0) {
alert("Password cannot be empty");
submitOK = false;
}
if (pass != rpass) {
alert("passwords don't match");
submitOK = false;
}
return submitOK;
}
<h1>Register</h1>
<br />
<form action="RegInt.jsp" method="post" onsubmit="return validate()">
Enter UserName :
<input type="text" name="uname" id="uname" value='${ param.uname}' placeholder="Enter Name">
<br/>
<br/>Enter Email:
<input type="email" name="email" id="email" value='${param.email}' placeholder="Enter Email">
<br/>
<br/>Enter Password:
<input type="password" name="pass" id="pass" value='${param.pass}' placeholder="Enter password">
<br/>
<br/>Repeat Password:
<input type="password" name="rpass" id="rpass" value='${param.rpass}' placeholder="Repeat Password" />
<br/>
<br/>
<br/>
<input type="submit" />
</form>
First check the spelling s and correct them. Then comment all the feilds and start troubleshooting them line by line. You will win. Regards !
Related
Why my form is getting submitted even if I leave all fields empty. I can't figure out what the problem is. The if loops looks fine to me.
This is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);">
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value == "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length == 0)
{
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!(form.phoneno.match(phoneno))
{
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw= /^[A-Za-z]\w{4,14}$/;
if(!(form.pass.match(passw)))
{
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))){
alert("You have entered an invalid email address!")
return false;
}
}
</script>
</body>
</html>
you are missing a ) in this line
if(!(form.phoneno.match(phoneno)))
Your code was just riddled with errors so I've sorted most of them here :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);" >
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value === "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length === 0) {
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!(form.phoneno.match(phoneno))) {
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw = /^[A-Za-z]\w{4,14}$/;
if (!(form.pass.match(passw))) {
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))) {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
</body>
</html>
Working fiddle here : https://jsfiddle.net/chj8rpxv/1/
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</body>
How can I make password field to check each other that the value written by user matches ?
function checkPassword(form) {
pOne = form.pOne.value;
pTwo = form.pTwo.value;
// If password not entered
if (pOne == '')
alert("Please enter Password");
// If confirm password not entered
else if (pTwo == '')
alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
// alert ("\nPassword did not match: Please try again...")
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password does not match!"
}
}
// If same return True.
else {
document.querySelector(".submit").addEventListener("click", print)
function print() {
return document.querySelector(".pass").textContent = "Your password match perfectly!"
}
}
}
<form class="formtwo" onsubmit="checkPassword(this)">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You need to add the event listener to the form submit before you test
window.addEventListener("load", function() {
document.getElementById("formtwo").addEventListener("submit", function(e) {
const pOne = this.pOne.value;
const pTwo = this.pTwo.value;
const pass = document.querySelector(".pass");
let errors = [];
// If password not entered
if (pOne == '') errors.push("Please enter Password");
if (pTwo == '') errors.push("Please enter confirm password");
if (pOne != pTwo) errors.push("Password did not match: Please try again...")
if (errors.length > 0) {
e.preventDefault(); // this will stop submission
alert(errors.join("\n"))
pass.textContent = "Your password does not match!"
return;
}
pass.textContent = "Your password match perfectly!"
})
})
<form id="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">djkakj</p>
<button type="submit" class="submit">Submit</button>
</form>
You can check my solution. Hope it's easier to understand. There were some issues in your code.
If you want to prevent the form submit if the password doesn't match then you need to use event.preventDefault to prevent the default behaviour.
You can fire the submit event once and then check for your required values.
const form = document.querySelector('.formtwo');
form.addEventListener('submit', checkPassword);
function checkPassword(e) {
e.preventDefault();
let pOne = form.pOne.value;
let pTwo = form.pTwo.value;
// If password not entered
if (pOne == "") alert("Please enter Password");
// If confirm password not entered
else if (pTwo == "") alert("Please enter confirm password");
// If Not same return False.
else if (pOne != pTwo) {
document.querySelector(".pass").textContent =
"Your password does not match!";
}
// If same return True.
else {
document.querySelector(".pass").textContent =
"Your password match perfectly!";
// submitting form
form.submit();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="formtwo">
<input type="email" name="email" placeholder="Email"><br>
<input type="password" name="pOne" placeholder="Password">
<input type="password" name="pTwo" placeholder="Re-Type Password">
<p class="pass">Password matching status</p>
<button type="submit" class="submit">Submit</button>
</form>
</body>
</html>
Working on a simple registration form in Javascript and I can't quite figure out why my phone validation function isn't working. What I'm trying to do is
Make the field optional. If the user doesn't put anything in the field, the form will still be valid and submit
If the user puts in a phone number, it must be in an XXX-XXX-XXXX format.
Any and all help is appreciated.
Here is my code
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if (username.value.length < 8) {
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild) {
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
}
function validatePhone() {
var num1 = document.getElementById('phone').value;
if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/)) {
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY', true).isVaild();
if (isVaild) {
return true;
} else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth">
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
The function validate validatePhone() will never be called due to
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
onsubmit will should be added to <form> and in the end of validateform add
return validatePhone()
And correct regex is following
^(\d{3}-){2}\d{4}$
The last problem is using match() match always return array which is always trucy. Even Boolean([]) will be true. So !num1.match(/\(\d{2}\)\d{8}/ will always be false. You should use RegExp.prototype.test.
if (num1 !== "" && !/(\d{3}-){2}\d{4}/.test(num1))
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if(username.value.length < 8){
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild)
{
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
return validatePhone();
}
function validatePhone()
{
console.log('x')
var num1 = document.getElementById('phone').value;
if (num1 !== "" && !/(\d{3}-){2}\d{4}/.test(num1))
{
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY' , true).isVaild();
if (isVaild) {
return true;
}
else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth" >
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
Your regex is incorrect. Try /^\d{3}-\d{3}-\d{4}$/.
The regex you provided will match any number of the format (##)########
function validateform() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var dob = document.getElementById('dob');
var email = document.getElementById('email');
var phone = document.getElementById('phone');
if (username.value.length < 8) {
alert("Username must be at least 8 characters");
username.focus();
return false;
}
if (password.value.length < 8) {
alert("Password must be at least 8 characters");
password.focus();
return false;
}
let isVaild = moment(dob.value, 'MM/DD/YYYY', true).isValid()
if (!isVaild) {
alert("Date must be in MM/DD/YYYY format");
dob.focus();
return false;
}
}
function validatePhone() {
var num1 = document.getElementById('phone').value;
if (num1 !== "" || !num1.match(/\(\d{2}\)\d{8}/)) {
alert('That is not a correct telephone number format');
return false;
}
}
function vailddatecheck(dateString) {
var dateforvailidation = dateString.value;
var isVaild = moment(dateforvailidation, 'MM/DD/YYYY', true).isVaild();
if (isVaild) {
return true;
} else {
alert("Date must be in MM/DD/YYYY format");
form.dob.focus();
return false;
}
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Totally Legit Registration Page</title>
<link href="Mod4style.css" rel="stylesheet">
</head>
<body>
<form class="submit.html" method="post" class="simpleForm" onsubmit="return validateform()">
<input type="text" id="username" placeholder="User Name">
<p class="error"></p>
<input type="password" id="password" placeholder="Password">
<p class="error"></p>
<input type="firstname" id="firstname" placeholder="First Name">
<p class="error"></p>
<input type="lastname" id="lastname" placeholder="Last Name">
<p class="error"></p>
<input type="dob" id="dob" placeholder="Date of Birth">
<p class="error"></p>
<input type="email" id="email" placeholder="Email">
<p class="error"></p>
<input type="phone" id="phone" placeholder="Phone Number" onsubmit="return validatePhone();">
<p class="error"></p>
<button type="Submit" onClick="">Submit</button>
<button type="Reset">Reset</button>
</form>
<script <script src="formvalidation.js" charset="utf-8"></script>
</body>
<script src="https://cdn.jsdelivr.net/npm/moment#2.24.0/moment.min.js"></script>
</html>
I'm trying to create a form validation using HTML and pure JavaScript as a part of my assignment. However, the age and password validation don't seem to work even with tinkering a lot with code. The age is supposed to be valid if it is between 18 to 60 and the password must be the same as well as according to regex.
Here's the extended code:
Edit: the uage code has been edited but still doesn't work as intended.
function checkPassword(str) {
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
}
function checkName(str) {
var ge = /^[a-zA-Z ]+$/;
return ge.test(str);
}
function mytq() {
var uname = document.forms.formvalidation.fullname;
var uemail = document.forms.formvalidation.email;
var uage = document.forms.formvalidation.age;
var upwd = document.forms.formvalidation.password;
var vpwd = document.forms.formvalidation.pwdrpt;
if (uname.value != "") {
if (!checkName(uname.value)) {
window.alert("Please enter a valid name");
uname.focus();
return false;
}
}
if (!(uage < 16 || uage > 60)) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}
if (uemail.value.indexOf("#", 0) < 0 && uemail.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid email");
uemail.focus();
return false;
}
if (upwd.value != "" && upwd.value == vpwd.value) {
if (!checkPassword(upwd.value)) {
window.alert("The password you entered is not valid");
upwd.focus();
return false;
}
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript">
</script>
</head>
<body>
<form name="formvalidation" method="POST" onsubmit="return mytq();" action="#">
<h1>Welcome to FTN.</h1>
<p>Fill this form before</p>
<hr>
<label for="name"><b>Full Name</b></label>
<input type="text" name="fullname" placeholder="Full Name" required>
<label for="email"><b>Email</b></label>
<input type="text" name="email" placeholder="Email" required>
<label for="age"><b>Age</b></label>
<input type="number" name="age" required>
<label for="password"><b>Password</b></label>
<input type="password" name="password" placeholder="Password" required>
<label for="password-repeat"><b>Re-type password</b></label>
<input type="password" name="pwdrpt" placeholder="Re-type Password" required>
<hr>
<p>By creating this account, you are agreeeing our terms and condition</p>
<button type="submit" class="registerbtn">Submit</button>
</form>
</body>
</html>
Your age comparison is flawed. If you wish to ensure that the age is greater than 16 and less than 60, you should simplify it to
if(uage < 16 || uage > 60) {
window.alert("Sorry you're not eligible for the position");
uage.focus();
return false;
}
I know there's a few similar questions to mine but none give me an answer.
My stopped validating the user input and goes straight to Activation.php
It worked at the beginning but then i added my captcha if statement and it stopped.
any ideas why itsnt working anymore ??
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/1999/xhtml
http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd"
>
<head>
<link rel="stylesheet" type=text/css" href="stylesheet.css">
<script>
function validateForm() {
var username = document.Register.uname;
var password = document.Register.pword;
var email = document.Register.email;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,41}$/;
var str1 = removeSpaces(document.getElementById('captchaimg').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (username.value == "")
{
alert("Username is required.");
username.focus();
return false;
}
if (password.value == "")
{
alert("Please enter a password.");
password.focus();
return false;
}
if (!passw.test(password.value))
{
alert("Password must consist of 8 to 41 characters, contain at least on digit and at least 1 upper case character");
password.focus();
return false;
}
if (email.value == "")
{
alert("Please enter your email address.");
email.focus();
return false;
}
if (!filter.test(email.value ))
{
alert("Please enter a valid email address.");
email.focus();
return false;
}
if (str1 != str2)
{
alert("Captcha is incorrect");
return false;
}
else{
return true;
}
}
</script>
</head>
<body>
<form action="Activation.php" name="Register" accept-charset="UTF-8" method = 'POST'onsubmit = "return validateForm()">
E-mail: <input type="text" name="email" id = "emailid" value="<?PHP if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>" size= "30" maxlength="30" ><br><br>
Username: <input type="text" name="uname" id = "unameid" value="<?PHP if(isset($_POST['uname'])) echo htmlspecialchars($_POST['uname']); ?>" > <label id="UserLabelId"><>
<br><br>
Password: <input type="password" maxlength="8" name="pword" id = "pwordid" value="<?PHP if(isset($_POST['pword'])) echo htmlspecialchars($_POST['pword']); ?>" size= "25" maxlength="25" ><br><br>
Enter Captcha code below: </br>
<img src ="captcha.php?rand=<?php echo rand();?>" id='captchaimg'><br>
<input id="6_letters_code" id="txtInput" name="6_letters_code" type="text" value="<?PHP if(isset($_POST['6_letters_code'])) echo htmlspecialchars($_POST['6_letters_code']); ?>" placeholder="Type captcha here" ><br>
<input type="hidden" id="txtCaptcha" /></label>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small> </br>
<input type="submit" value="Register" name="submit" class="quoteButton">
</form>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha(){
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>`enter code here`
You have 2 IDs on :
<input id="6_letters_code" id="txtInput" name="6_letters_code" type="text" value="<?PHP if(isset($_POST['6_letters_code'])) echo htmlspecialchars($_POST['6_letters_code']); ?>" placeholder="Type captcha here" ><br>
I'm pretty sure XHTML 1.0 will only take the first ID associated with this element so that it will never see the txtInput ID?
Also, for STRING comparisons in JS you'll want to use !== or === for if (str1 != str2) it's very inconsistent whether it will work with a double == or !=.
If those don't solve your issues then let me know.
The problem seems to be in my captcha validation part.
Once i commented out the below it worked fine.
Thanks everyone, please let me know if you know how to validate a captcha in javascript!
//var str1 = removeSpaces(document.getElementById('captchaimg').value);
//var str2 = removeSpaces(document.getElementById('6_letter_code').value);
and
/* if (str1 !== str2)
{
alert("Captcha is incorrect");
return false;
}*/