My form validation used to work but now I cannot figure out what is wrong.
When entering an email or username you always get a pop-up with the error
Username or Email is needed
Remove each check one by one and you get the next error message
<form method='POST' name='signIn' onsubmit='return checkLoginForm(this);'>
<input type='hidden' name='action' value='signIn'>
<div class='enterInfo' align='left'>Username or Email 1:</div><input size='60' type='text' name='username' class='input' id='theFieldID'></div>
<div class='enterInfo' align='left'>Password: <input id='username' size='60' type='password' name='pswd' class='input'></div>
<div class='agreement' align='left'> </div>
<input type='submit' value='Log In'>
</form>
Here is the js
function checkLoginForm(form) {
if(form.username.value == "") {
alert("Username or Email is needed");
form.username.focus();
return false;
}
if(form.username.value.length < 4) {
alert("Username or Email is to short");
form.username.focus();
return false;
}
re = /^[-_a-zA-Z0-9.,##!?]*$/;
if(!re.test(form.username.value)) {
alert("Username or Email only contains letters, numbers and _-.,##!?");
form.username.focus();
return false;
}
if(form.pswd.value == ""){
alert("Password is needed");
form.pwd1.focus();
return false;
}
return true;
}
The best way to access to this kind of elements is By Id. Also, for more optimization and comfortable, it's better to assign a variable to the element one time and use that variable for the next times:
function checkLoginForm(form) {
usn = document.getElementById("theFieldID");
pwd = document.getElementById("password");
if(usn.value == "") {
alert("Username or Email is needed");
usn.focus();
return false;
}
if(usn.value.length < 4) {
alert("Username or Email is to short");
usn.focus();
return false;
}
re = /^[-_a-zA-Z0-9.,##!?]*$/;
if(!re.test(usn.value)) {
alert("Username or Email only contains letters, numbers and _-.,##!?");
usn.focus();
return false;
}
if(pwd.value == ""){
alert("Password is needed");
pwd.focus();
return false;
}
return true;
}
<form method='POST' name='signIn' onsubmit='return checkLoginForm(this);'>
<input type='hidden' name='action' value='signIn'>
<div class='enterInfo' align='left'>Username or Email 1:</div><div>
<input size='60' type='text' name='username' class='input' id='theFieldID'></div>
<div class='enterInfo' align='left'>Password: <input id='password' size='60' type='password' name='pswd' class='input'></div>
<div class='agreement' align='left'> </div>
<input type='submit' value='Log In'>
</form>
For this kind of thing:
if(form.username.value == "") {
alert("Username or Email is needed");
form.username.focus();
return false;
}
You are better off directly accessing the object:
if(document.getElementById("theFieldID").value == "") {
alert("Username or Email is needed");
form.username.focus();
return false;
}
In any case, you need to pay attention to what your names and IDs are on those elements. For instance, you are passing in "form" as an argument, but with no name or ID specified, there is nothing to tell it which form you are talking about.
input type ="submit" will submit the form ,
You need to use event.preventDefault to prevent the default behavior and to perform validation
Also form.username.focus() & form.username.focus(); will throw not a function error
You need use document.getElmentById(someElement').focus()
JSFIDDLE
Use this code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function checkLoginForm() {
var eleuser = document.forms["signIn"]["username"];
var elepass = document.forms["signIn"]["pswd"];
var username = eleuser.value;
var pass = elepass.value;
if(username == "") {
alert("Username or Email is needed");
eleuser.focus();
return false;
}
if(username.length < 4) {
alert("Username or Email is to short");
eleuser.focus();
return false;
}
re = /^[-_a-zA-Z0-9.,##!?]*$/;
if(!re.test(username)) {
alert("Username or Email only contains letters, numbers and _-.,##!?");
eleuser.focus();
return false;
}
if(pass == ""){
alert("Password is needed");
elepass.focus();
return false;
}
return true;
}
</script>
<form method="post" name='signIn' onsubmit='return checkLoginForm();'>
<div class='enterInfo' align='left'>Username or Email 1:</div>
<input size='60' type='text' name='username' class='input' id='theFieldID'>
<div class='enterInfo'> Password: </div>
<input id='username1' size='60' type='password' name='pswd' class='input'>
<br><br>
<input type='submit' value='Log In'>
</form>
</body>
</html>
Related
Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>
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>
<html>
<head>
</head>
<body>
<script>
function myFun(){
var correct_way = /^[A-Za-z0-9]+$/;
var a = document.getElementById("User_Name").value;
if(a=="") {
document.getElementById("Message").innerHTML="Please enter a username.";
return false;
}
if(a.length<5){
document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
return false;
}
if(a.match(correct_way))
document.location.href = "test1.html";
else{
document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
return false;
}
}
</script>
<form onsubmit="return myFun()">
<input type="text" id="User_Name" value=""></input>
<br></br>
<span id="Message"> </span>
<br></br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>
Hello, I have created a username validation code. The validation does work however, the user is not redirected to the 'test1.html' document. They are both in the same folder. How do i make it redirect after the validation is checked?
You should return true at the end of function myFun.
HTML
<form action="test1.html" onsubmit="return myFun()">
<input type="text" id="User_Name" value="" />
<span id="Message"> </span>
<input type="submit" value="Submit" />
</form>
Updated code
function myFun(){
var correct_way = /^[A-Za-z0-9]+$/;
var a = document.getElementById("User_Name").value;
if(a=="") {
document.getElementById("Message").innerHTML="Please enter a username.";
return false;
}
if(a.length<5){
document.getElementById("Message").innerHTML="Please enter a username with 5 or more characters";
return false;
}
if(a.match(correct_way)){
alert("Sucessful Login, welcome to BREAKOUT!");
}
else{
document.getElementById("Message").innerHTML="Please enter a username with only letters and integers";
return false;
}
return true;
}
jsFiddle demo - http://jsfiddle.net/h67q09mp/
i dont understand what am i doing wrong here.... tried almost everything still the form is being submitted without validation. i dont know what's causing the problem here been working on this for past 4 hours, everytime i click on the submit button it goes straight to the submission successful page... can anyone help me with this?
<script type ="text/javascript">
function validate(){
if(document.orderForm.firstName.value=="" ){
document.getElementById('errors').innerHTML = "Please Enter a First Name";
document.orderForm.fistName.focus();
return (false);
}
if(document.orderForm.lastName.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a Last Name";
document.orderForm.lastName.focus();
return (false);
}
if(document.orderForm.address.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a address");
document.orderForm.address.focus();
return (false);
}
if(document.orderForm.city.value == "" ){
document.getElementById('errors').innerHTML = "Please Enter a City");
document.orderForm.city.focus();
return (false);
}
if(document.orderForm.postalCode.value == "" ||
document.orderForm.postalCode.value.length != 6 ){
document.getElementById('errors').innerHTML = "Please Enter a correct PostalCode");
document.orderForm.postalCode.focus();
return (false);
}
if(document.orderForm.province.value == "Select" ){
document.getElementById('errors').innerHTML = "Please Select your province")
return (false);
}
if(document.orderForm.widget1qty.value == "0" || document.orderForm.widget1qty.value == "" &&
document.orderForm.widget2qty.value == "0" || document.orderForm.widget2qty.value == "" &&
document.orderForm.widget2qty.value == "0" || document.orderForm.widget2qty.value == "" ){
document.getElementById('errors').innerHTML = "Please Select at least one item")
return (false);
}
else
{
return(true);
}
}
</script>
<form name="orderForm" method="POST" action="processForm.html" onSubmit="return validate();">
refer this Sample code,definitely Solve your problem
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
function validate()
{
if( document.myForm.Name.value == "" )
{
document.getElementById("errors").innerHTML = "Please enter first name";
document.myForm.Name.focus() ;
return false;
}
return( true );
}
//-->
</script>
</head>
<body>
<form action="processForm.html" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<div id="errors"></div>
</body>
</html>
Please use below code. it is working fine.
function validate() {
if (document.orderForm.firstName.value=="" ) {
document.getElementById("errors").innerHTML = `Please enter first name`;
document.getElementById("firstName").focus();
return (false);
}
}
<form name="orderForm" onSubmit="return validate();">
<input type="text" id="firstName" />
<input type="submit" id="btnSubmit" value="submit" />
<div id="errors"></div>
</form>
http://www.sharepointprog.com
I am trying to validate the password field using javascript. Making sure when the user retypes the password in the confirm password field, it should be the same.
here is what i tried to do. This is the form. The onsubmit = "validate_reg()" is another validation using javascript to make sure all the fields must be filled.
<form name="register" action="signup.php" onsubmit="return validate_reg()"enctype="multipart/form-data" method="post" >
<table width="600" border="0">
<tr><td width="210" height="45">Username*:</td><td>
<input type="text" size="40" name="userUsername" id="user_username" /></td></tr>
<tr><td width="210" height="45">Password*:</td><td>
<input type="password" size="40" name="userPassword" id="user_password"/></td></tr>
<tr><td width="210" height="45">Re-type Password:</td><td>
<input type="password" size="40" name="userPasswordConfirm"
id="user_password_confirm"/></td></tr>
</table>
</form>
This is the javascript codes:
<!--================Javascript for the validation of the Password Confirmation==========================-->
<script type="text/javascript" language="javascript">
function validatepw() {
if ( document.register.user_password.value != document.register.user_password_confirm.value)
{
alert('Passwords did not match!');
return false;
}else{
document.register.submit();
return true;
}
}
</script>
<!--================Javascript for the validation of the required fields ================================-->
<script type="text/javascript">
function validate_reg()
{
var isValid = true;
// using OLD method of using name to find the control
if ( document.register.user_username.value == "")
{
document.register.user_username.style.backgroundColor="red";
isValid=false;
}
else{
document.register.user_username.style.backgroundColor="white";
}
if ( document.register.user_password.value == "")
{
document.register.user_password.style.backgroundColor="red";
isValid=false;
}
else{
document.register.user_password.style.backgroundColor="white";
}
if ( document.register.user_password_confirm.value == "")
{
document.register.user_password_confirm.style.backgroundColor="red";
isValid=false;
}
else{
document.register.user_password_confirm.style.backgroundColor="white";
}
}
</script>
where are you calling validatepw?
could add onchange="javascript:validatepw()" to both pwd fields