I have done a login page. I want my js validateForm()function to alert a user if they have left out the username or password. This is the code I have got at the moment.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("Please enter username");
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<form name="myform" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
At the moment it is not working, and I think the problem is with the code line "var x=document.forms["myForm"]["username"].value;" Can someone please help?
The issue is forms["myForm"], you used an uppercase F, when actually your form name is all lowercase so it should be:
var x=document.forms["myform"]["username"].value;
// ^ lowercase
Not part of the problem, but you might prefer to use unobtrusive JavaScript to set the onsubmit handler instead of in the HTML attribute:
window.onload = function(){
document.forms["myform"].onsubmit = validateForm;
};
Now, in validateForm you can use this instead of finding the form manually.
function validateForm()
{
var x = this["username"].value;
...
}
Related
I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>
Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>
I'm trying to create a simple registration form with basic HTML and PHP to insert data to my database. Basically, I want to validate the fields first before inserting the data and so I have created an external JavaScript file. Problem is, it is displaying the actual JavaScript code on the next page as opposed to validating!
My HTML file:
<html>
<head>
<title>Register Page</title>
<body>
<form id="register" method="POST" action="register.js" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</head>
</html>
My JavaScript file:
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
Instead of just validating I'm being redirected to a new webpage showing me the code I have written above.
I am completely new to web development and it would mean a lot if someone could help me out. All I want to do is just validate the fields before adding them to the database.
Two things you have to change
add id to your input control because you are fetching the value of text through Id
<input type="text" name="forename" id="forename">
syntax of getElementById()
var forename = document.getElementById("forename").value;
Once You do the validation for username and password. Submit the form
<script type="text/javascript">
function verify(){
var forename = document.getElementById("forename").value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
<form id="register" method="POST" onsubmit="return verify()" action="register.php">
Forename: <input type="text" id="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
I think you should recheck your syntax for document.getElementById["forename"]
It should be document.getElementById("forename")
You can try debugging step wise. For example, try console.log.
var forename = document.getElementById("forename").value;
console.log(forename);
Try Chrome/Firebox Inspect element > Console and see if anything is been printed.
Hope this helps.
Peace! xD
You shouldn't be declaring register.js as the action for your <form>. The action attribute of a <form> element tells the browser where to send (POST or GET) the form data to, which is why you're being taken to register.js in your browser.
You need to intercept the browser submitting the form, do your validation, and then send the data on to your PHP file (register.php). It might be worth reading some tutorials on javascript form validation, such as this TutorialsPoint one.
What you can be able to do is to take your hole script into a echo in php, then create a php validation for the js and check if js got successfully done then execute script if so.
if you want your javascript on same html page then put this type
<html>
<head>
<title>Register Page</title>
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
</head>
<body>
<form id="register" method="POST" action="" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
I'm trying to make a password field for a webpage. So far I have:
<form name="PasswordField" action="">
Password:
<input type="password" name="password">
<input type="button" value="Log in">
</form>
Pathetic I know. It doesn't have to be fancy, I just need it to "get" the password from the textbox and match it against the password for the page. I'm assuming I can use an if-else?
*Code for get password from textbox when the "Log in" button is pressed here*
if (password = "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
Sadly I've been fooling with this for hours. I tried functions, too, and that didn't seem to work (for me) either.
If you go that route, you need to put the validation inside a function that gets called in the onclick event of your button. Also to access the password <input node in js, you can give it an id and use document.getElementById(id). Also, = is an assignment operator. Use == for comparison :)
<head>
<script type="text/javascript">
function isValid(){
var password = document.getElementById('password').value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>
<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid();">
</form>
Or an even easier way would be to pass the password DOM node as an argument to the function:
<head>
<script type="text/javascript">
function isValid(myNode){
var password = myNode.value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>
<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid(this);">
</form>
Is this what you are looking for?
document.forms['PasswordField'].elements['password'].value
I used jquery and here's my solution:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input[name='login']").click(function() {
var s = $("input[name='password']").val();
if(s == "rawr") {alert('Correct!')}
else {alert('Wrong Password')}
});
});
</script>
</head>
<body>
<form name="PasswordField" action="">
Password:<input type="password" name="password">
<input type="button" value="Log in" name="login">
</form>
</body>
</html>
Im Looking for a simple solution to stop a login form from submitting with empty input fields. The code for the form is below. I would like to use a simple Javascript soluiton if possible.
<form id="login" method="post" action="">
<input type="text" name="email" id="email" />
<input type="password" name="pwd" id="pwd" />
<button type="submit" id="submit">Login</button>
</form>
If possible I would also like to change the border of the empty field(s).
Thanks in advance.
Sample code with dummy checks:
<script type="text/javascript">
function checkForm(form) {
var mailCheck = checkMail(form.elements['email']),
pwdCheck = checkPwd(form.elements['pwd']);
return mailCheck && pwdCheck;
}
function checkMail(input) {
var check = input.value.indexOf('#') >= 0;
input.style.borderColor = check ? 'black' : 'red';
return check;
}
function checkPwd(input) {
var check = input.value.length >= 5;
input.style.borderColor = check ? 'black' : 'red';
return check;
}
</script>
<style type="text/css">
#login input {
border: 2px solid black;
}
</style>
<form id="login" method="post" action="" onsubmit="return checkForm(this)">
<input type="text" name="email" id="email" onkeyup="checkMail(this)"/>
<input type="password" name="pwd" id="pwd" onkeyup="checkPwd(this)"/>
<button type="submit" id="submit">Login</button>
</form>
Possible approach:
setting action to #
adding handler to the submit button or the onsubmit of the form
change the action of the form, if text fields are not empty
Edit: To make this even work for non-javascript users insert the #-action when page is loaded.
To keep it minimal I would just use:
<form id="login" method="post" action="" onSubmit="if (this.email.value == '' || this.pwd.value == '') {return false;}">
Granted - doesn't point out what's amiss to the user, but works a treat.