<script>
function validate() {
var username = document.getElememtById("uname");
var password = document.getElememtById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
}
}
</script>
<form>
<input id="uname" type="text" placeholder="username"></input>
<input id="pass" type="password" placeholder="password"></input>
<button onclick="validate()" type="submit">Submit</button>
</form>
Prevent the default behavior using e.preventDefault and also there is typo in getElememtById
function validate(e) {
e.preventDefault();
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
}
}
<form>
<input id="uname" type="text" placeholder="username" />
<input id="pass" type="password" placeholder="password" />
<button button type='submit' onclick="validate(event)" type="submit">Submit</button>
</form>
There are a few issues on your code:
1) The input tag do not use a close tag like </input>
2) You need to pass event as the argument of your custom function and then call event.preventDefault() to prevent the default submit event associated with the form.
3) getElememtById() is actually named like getElementById()
Working example:
function validate(event)
{
event.preventDefault();
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "")
{
alert("no data");
}
}
<form>
<input id="uname" type="text" placeholder="username">
<input id="pass" type="password" placeholder="password">
<button onclick="validate(event)" type="submit">Submit</button>
</form>
You have typo in getElememtById, should be getElementById. You also have to prevent the default event if condition is true.
Please Note: input is called empty or void element and only have a start tag since they can't have any content. Using closing tag in empty element is a bad parctice.
<script>
function validate(e) {
use
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value == "" || password.value == "") {
alert("no data");
e.preventDefault();
}
}
</script>
<form>
<input id="uname" type="text" placeholder="username"/>
<input id="pass" type="password" placeholder="password"/>
<button onclick="validate(event)" type="submit">Submit</button>
</form>
Related
the code below was written to validate simple html form with JavaScript and preventDefault() method means that if the required fields are empty then stop form submission and display error or otherwise submit the form if the required fields are not empty.
The problem comes when I click the submit button the form isn't working.
Can anyone please help me to solve the problem?
let form = document.getElementById("signUp");
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
function validateForm() {
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
e.preventDefault();
validateForm();
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
With e.preventDefault() you say that the form should not be submitted.
So you only want to call if in case the validation returns false.
Besides that, your uname and uemail is set before the form is submitted. So it won't contain the state of the input fields at the time the form is submitted. You have to move them into your validateForm function.
let form = document.getElementById("signUp");
function validateForm() {
let uname = document.forms["myForm"]["userName"].value;
let uemail = document.forms["myForm"]["userEmail"].value;
if (uname == " ") {
alert("Name is Empty");
} else if (uemail == " ") {
alert("Email is Empty");
return false;
}
return true;
}
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName">
<br> Email: <input type="email" name="email" id="userEmail">
<button type="submit">sign up</button>
</form>
And uname == " " does not test if the name is empty. It tests if it consists of one character that is a space. The same is for uemail == " ". You probably looking for uname.trim() == ""
As you need to verify the data on the server anyways. And in some way need to display an error if the validation fails on the server side.
It is often sufficient to rely on the HTML solutions to verify the form data (if the browser support is decent enough even if it is not complete).
Something like this:
.error {
display: none;
}
input:not(:placeholder-shown):invalid +.error {
display: block;
}
<form id="signUp" name="myForm">
Name: <input type="text" name="uname" id="userName" placeholder="Name" pattern="^(?!^ +$)([\w -&]+)$" required>
<div class="error">Name must not be empty</div>
<br> Email: <input type="email" name="email" id="userEmail" placeholder="Email" required>
<div class="error">Email must be valid</div>
<button type="submit">sign up</button>
</form>
const form = document.getElementById("signUp");
form.addEventListener("submit", (e) => {
e.preventDefault();
if(validate()) {
form.submit()
}
});
const validate = () => {
const name = document.querySelector("#userName");
const email = document.querySelector("#email");
let hasError = false;
if(!(name.value && name.value.length > 4)) {
const nameErr = document.querySelector("#user-name-error");
nameErr.textContent = "Name is required";
hasError = true;
}
if(!(name.value && name.value.length > 0)) {
const emailErr = document.querySelector("#user-email-error");
emailErr.textContent = "Email is required";
hasError = true;
}
return !hasError;
};
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" />
<p id="user-name-error" style="color: red;"></p>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" />
<p id="user-email-error" style="color: red;"></p>
</div>
<button type="submit">sign up</button>
</form>
<form id="signUp" name="myForm">
<div class="form-group">
<label for="userName">Name: </label>
<input type="text" name="uname" id="userName" required minlength="4"/>
</div>
<div class="form-group">
<label for="userEmail">Email: </label>
<input type="email" name="email" id="email" required pattern="[^#]*#[^.]*\..*"/>
</div>
<button type="submit">sign up</button>
</form>
This is an example using only html, it is only for your use case of course if you want to add more complexe validation use javascript
I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp
I have this javascript below:
<script type="text/javascript">
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
if(password.value!= vpassword.value){
document.getElementById("button1").disabled = true;
}
}
</script>
HTML code:
Password: <input type="password" name="password" id="password" required onchange='PassCheck();'/> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();'/> <br>
<input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();'/>
The submit button is disabled only the first time and the disbale button doesn't work after second attempt. I am not sure why its not working. Please help! Thanks in advance.
You simply need to add an else condition that re-enables your button once the values match:
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
if (password.value != vpassword.value) {
document.getElementById("button1").disabled = true;
}
else {
document.getElementById("button1").disabled = false;
}
}
Password: <input type="password" name="password" id="password" required onchange='PassCheck();' /> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();' /> <br>
<input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();' />
onchange occurs only when the element loses focus, so try to use onkeyup or oninput events. Also don't forget to set disabled to false.
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
document.getElementById("button1").disabled = password.value.length === 0 ||
password.value != vpassword.value;
}
PassCheck();
Password: <input type="password" name="password" id="password" required onkeyup='PassCheck();'/> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onkeyup='PassCheck();'/> <br>
<input type="submit" value="Submit" id="button1" name="submit"/>
I'm working on a change password page. In this page the user enters the new password and confirms the new password. If both the passwords are not matching it should be in the same page. If the passwords match, then the user gets directed to another page. I have tried all methods to redirect the page , but it is not happening. Please help !
function f1()
{
var newpass = document.getElementById('npass').value;
var confirmpass = document.getElementById('cpass').value;
if(newpass!=confirmpass)
{
document.getElementById('npass').value = "";
document.getElementById('cpass').value = "";
alert("Password Mismatch. Please enter again!");
//window.location.href = "/file.html";
// window.location = 'file.html';
// window.location.replace('file.html');
//window.location.assign("file.html");
//window.location.href = "file.html";
}
else
{
alert("Password Match");
// window.location.href= "/file.html";
// document.write("check");
}
}
</script>
<form method="POST" onsubmit="f1()">
<label for="npass">New Password:</label>
<input type="password" id="npass" placeholder="Enter New Password"
name="newpassword" required="required" size="8">
<label for="cpass">Confirm Password:</label>
<input type="password" id="cpass" placeholder="Confirm New Password"
name="cpass" required="required" size="8"><br><br>
<input type="submit" class="btn btn-info" name="submit" value="Submit">
</form>
The alert boxes are working but the page redirect is not happening. I have tried all the redirect methods as shown in the code. But still not working. New to javascript. Please help
In your approach just returning false will help. This way you're avoiding the form submission.
function f1() {
var newpass = document.getElementById('npass').value;
var confirmpass = document.getElementById('cpass').value;
if (newpass != confirmpass) {
document.getElementById('npass').value = "";
document.getElementById('cpass').value = "";
alert("Password Mismatch. Please enter again!");
//window.location.href = "/file.html";
// window.location = 'file.html';
// window.location.replace('file.html');
//window.location.assign("file.html");
//window.location.href = "file.html";
} else {
alert("Password Match");
// window.location.href= "/file.html";
// document.write("check");
}
return false;
}
<form method="POST" onsubmit="return f1()">
<label for="npass">New Password:</label>
<input type="password" id="npass" placeholder="Enter New Password" name="newpassword" required="required" size="8">
<label for="cpass">Confirm Password:</label>
<input type="password" id="cpass" placeholder="Confirm New Password" name="cpass" required="required" size="8"><br><br>
<input type="submit" class="btn btn-info" name="submit" value="Submit">
</form>
On the other hand, if you have the control to redirect the user, why to use a form element. Do you want the default form validations? maybe! if that's not the case, you can remove the form element and bind a click event to your button.
function f1() {
var newpass = document.getElementById('npass').value;
var confirmpass = document.getElementById('cpass').value;
if (newpass.trim() === '') {
alert("Password is required.");
return;
}
if (confirmpass.trim() === '') {
alert("Password confirmation is required.");
return;
}
if (newpass != confirmpass) {
document.getElementById('npass').value = "";
document.getElementById('cpass').value = "";
alert("Password Mismatch. Please enter again!");
//window.location.href = "/file.html";
// window.location = 'file.html';
// window.location.replace('file.html');
//window.location.assign("file.html");
//window.location.href = "file.html";
} else {
alert("Password Match");
// window.location.href= "/file.html";
// document.write("check");
}
}
document.querySelector('.btn').addEventListener('click', f1)
<label for="npass">New Password:</label>
<input type="password" id="npass" placeholder="Enter New Password" name="newpassword" required="required" size="8">
<label for="cpass">Confirm Password:</label>
<input type="password" id="cpass" placeholder="Confirm New Password" name="cpass" required="required" size="8"><br><br>
<input type="submit" class="btn btn-info" name="submit" value="Submit">
You are calling the function in the submit event of the form so this happens:
Your JavaScript tells the browser to navigate to X
The form submission tells the browser to navigate to Y
The browser navigates to Y
You need to prevent the default behaviour of the form submission to allow the navigation in step 1 to be followed through on.
Using an intrinsic event attribute, you need to return false; at the end of your onsubmit function. That could be by returning the return value of f1 and then returning false from there, or a second statement in the function.
A modern approach (i.e. the best practice for this century) would replace the onsubmit attribute with addEventListener and then call the preventDefault method of the event object.
i am having this problem when i submit the form where both the password and username is wrong. I get an alert box saying that i have enter the wrong details. But when the username is correct and password is validation is wrong it will give me an arlet box by when pressed ok it will submit the form even when i have returned false.
Help please much appreciated
<script type="text/javascript">
function validate(form_id, firstName, password){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.forms[form_id].elements[firstName].value;
var password = document.forms[form_id].elements[password].value;
if (Reg.test(username) == false) {
alert('Invalid Username.');
document.forms[form_id].elements[firstName].focus();
return false;
}
if (Reg1.test(password) == false) {
alert('Invalid Password.');
document.forms[form_id].elements[password].focus();
return false;
}
}
</script>
<form id="form_id" action="userlogininput.cgi" onsubmit="javascript:return validate('form_id','firstName','password');" name="form" method="post">
Username : <input type="text" id="firstName" name="firstName" class="textboxH-300" required><br>
Password : <input type="password" id="password" name="password" class="textboxH-300" required><br><br>
<input id="submitbtn" type="submit" value="Submit"/>
</form>
You can use e.preventDefault() to prevent form sending.
Here is a code example
(function(){
function validate(e) {
e.preventDefault(); // prevent the form sending
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = document.getElementById('firstName');
var password = document.getElementById('password');
if (Reg.test(username.value) == false) {
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
alert('Invalid Password.');
password.focus();
return false;
}
}
//add event listener for form submission
document.getElementById('form_id').addEventListener('submit',validate);
})();
<form id="form_id" action="userlogininput.cgi" name="form" method="post">
Username :
<input type="text" id="firstName" name="firstName" class="textboxH-300" required>
<br> Password :
<input type="password" id="password" name="password" class="textboxH-300" required>
<br>
<br>
<input id="submitbtn" type="submit" value="Submit" />
</form>
Try prevent default event.
Bind function to the form submit event:
function validate(form){
var Reg = /^[A-Za-z0-9_]{1,20}$/;
var Reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
var username = form.querySelector('[name=firstName]');
var password = form.querySelector('[name=password]');
if (Reg.test(username.value) == false) {
event.preventDefault();
alert('Invalid Username.');
username.focus();
return false;
}
if (Reg1.test(password.value) == false) {
event.preventDefault();
alert('Invalid Password.');
password.focus();
return false;
}
}
<form onsubmit="validate(this)">
<input name="firstName">
<br>
<input name="password">
<br>
<button type="submit">submit</submit>
</form>