Form validation using html and javascript - javascript

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;
}

Related

Problem with phone number validation function

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>

How can i validate and alert if the phone has incorrect input?

The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

Simple JavaScript validation not working?

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

alert not displaying in JS

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 !

Categories

Resources