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.
Related
I have to do the validation of the input text field.
I would like Js to show an error message through the setCustomValidity() method.
Is it possible?
function checkName() {
var x = document.formUser;
var input = x.name.value;
if (input.length < 3) {
input.setCustomValidity('This field is invalidate');
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return validateForm();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="validateForm();">
</form>
You need to call reportValidity() on the input after setting the custom validity message.
Additionally you must call the reportValidity method on the same element or nothing will happen.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
function checkName() {
const inp = document.getElementById('name');
const val = inp.value;
if (val.length < 3) {
inp.setCustomValidity('This field is invalidate');
inp.reportValidity();
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return checkName();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="checkName();">
</form>
I would like to control more text input with javascript.
The setCustomValidity() method means that it will have to show an error message if input has less than three characters.
it doesn't always work.
Eg. If I put a string of one character in the first field and a string of four in the second field; it sends without showing the error. If I repeat the same test, it works.
Why?
window.onload = function() {
const field = document.getElementsByClassName("input-field");
for (let i = 0; i < field.length; i++) {
field[i].addEventListener('input', function() {
const val = field[i];
if (val.length < 3) {
field[i].setCustomValidity('Field is invalid');
}
})
}
}
<form name="formUser" id="formUser" action="#">
<div class="section">
<label for="fname">First name</label>
<input class="form-control input-field" type="text" id="fname" required>
<label for="lname">Last name</label>
<input class="form-control input-field" type="text" id="lname" required>
</div>
<input type="submit" class="btn btn-primary" value="Send">
You could add a <p class="error">...</p> inside your section div.
Hide it with css (display: none) and when you get an error in your validation add a class to that like "show" to show it (display: unset).
You can do custom form validation using Javascript like this.
Here I have just added a div with a warning and alert box. You can do whatever you want.
It will alert a warning if you will click on submit when fields were empty.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
let alertBox = document.getElementById("alert-box");
// Here instead of checking (x == " "), you can use your custom validations
if (x == "") {
alertBox.innerHTML = `<p>Form input are empty</p>`; // appends a div with warning
alert("Name must be filled out"); // alert box
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<div id="alert-box"> </div>
<form name="myForm" action="#" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
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;
...
}
Just a really simple login and redirect, but the script doesn't fire since I changed the button input type to 'submit' and the onClick event to onSubmit. All is does now is just add the username and password as a string to the url.
<form name="loginform">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login" onSubmit="validateForm();" />
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
window.location = "main.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this: <form name="loginform" onsubmit="validateForm()" method="post"> Here are some useful links:
JavaScript Form Validation
Form onsubmit Event
For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.
You can read more about the differences here.
UPDATE:
You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:
<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login"/>
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.
Option 1
<form name="loginform" onSubmit="return validateForm();">
Option 2
<input type="submit" value="Login" onClick="return validateForm();" />
<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;"> <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>
<form name="loginform" onsubmit="validateForm()">
instead of putting the onsubmit on the actual input button
Add a property to the form method="post".
Like this:
<form name="loginform" method="post">
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == null || username == "") {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
alert('Login successful');
}
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate();" />
Here is the related part of code:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" >
<div>
<hr/><a name="d2"></a>
<h2>CMS Sign In Page</h2>
<p>Passing parameters to the Web Service:</p>
<label>Your username: </label><input type="text" name="username" id="username" value="elthefar" />
<label>Your password: </label><input type="password" name="password" id="password" value="workandwork" />
<input type="button" value="Sign In" onclick="var r = SignIn(); if (r == 0) document.forms[0].action = 'temp2.jsp'; return true;" />
I want my form to forward to temp2.jsp if SignIn return 0, otherwise to temp.jsp. but the above code doesn't forward to any page.
You can add a onsubmit event to you form like this:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" onsubmit="return myfunction();">
and then use a simple submit button in your form.
<input type='submit' value='Sign In' />
in this case, when you click on submit button, the function will fire and in that function you can do what ever you want to do like this:
<script language='javascript'>
function myfunction(){
var r = SignIn();
if(r == 0)
document.forms[0].action = 'temp2.jsp';
return true;
}
</script>
Did you mean to use input type="submit"? Or call document.forms[0].submit();?
Change your form to this
<form id="frmDemo" name="frmDemo" method="post">
And change button to submit
<input type="submit" name="Submit" onClick="Validate()" value="Submit" />
And use your javaScript
<script language='javascript'>
function Validate(){
var r = SignIn(); // assuming, you have some implementation for SignIn() method
var frm = document.getElementById("frmDemo") || null;
if(frm) {
if(r != 0)
{
frm.action = 'temp.jsp';
}else{
frm.action = 'temp2.jsp';
}
}
}
</script>