Javascript form validation not working - javascript

I can't understand why my javascript isn't working... Do i need to declare a variable somewhere?
<script type="text/javascript">
function validation(form) {
      
if(form.first_name.value == '' ) {

alert('Please enter your first name');
 form.first_name.focus();
return false;
}
if(form.00N30000006S4uq.value == '') {

alert('Please enter the high end of your budget');
 form.company.focus();
return false;
}
return true;
}
</script>
<form action="https://www.salesforce.com/servlet/servlet.WebToLead" method="POST" onsubmit="return validation(this);">

As mentioned by #ReturnTrue, the NAME must begin with a letter. That is why your script is failing.
In your case since the field is auto-generated, if you know the flow of the elements in the form then you can reference the form elements array, like this...
form.elements[2].value
where form.elements[2] is form.00N30000006S4uq. That will do the job.
Example:
function validation(form) {
if(form.elements[0].value == '' ) {
alert('Please enter your first name');
form.first_name.focus();
return false;
}
if(form.elements[2].value == '') {
alert('Please enter the high end of your budget');
form.company.focus();
return false;
}
return true;
}
<form action="" method="POST" onSubmit="return validation(this);">
<input type="text" name="first_name" />
<input type="text" name="company" />
<input type="text" name="00N30000006S4uq" />
<input type="submit" name="submit" />
</form>

Form names need to begin with a letter. "00N30000006S4uq" fails because it begins with a number.
See: http://www.w3.org/TR/html401/types.html#type-cdata

Related

How do i make a js code that redirects to a certain html page with a certain input?

let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>

validate input with js

this is my register.php code
<form id="register_form" onsubmit="return false" autocomplete="off" >
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="enter username">
<small id="u_error" class="form-text text-muted"></small>
</div>
<button type="submit" name="user_register" class="btn btn-primary"><span class="fas fa-user"></span> Register</button>
this is my js
$(document).ready(function(){
// alert("hello friends");
$("register_form").on("submit",function() {
var status = false ;
var name = $("#username");
if (name.val() == "" || name.length < 6 ) {
name.addClass("border-danger");
$("#u_error").html("<span class='text danger'> name more that 6 char</span>");
status = false;
}else {
name.addClass("border-danger");
$("#u_error").html("<span class='test danger'> please enter name</span>");
status = true;
}
})
})
here i try username field less than 6 or empty through js i validate but its not working may i know why?
There are so many changes into you code.
1.html - add submit button with </form>
2.js - your event is on '#register_form' instead of 'register_form'
3.js - To prevent on submit you have to return true or false..in you case return status; after if-else
4.js - use name.val().length instead of name.length
Nothing happens because you are submitting the form, causing a redirect to another page or to the same page in order to do things with the backend on the server.
In order to prevent the form from submitting, do the following:
$("register_form").on("submit",function(event) {
event.preventDefault();
//... rest of your code
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Event.preventDefault()
Besides, you are now checking if the value of name is empty, or the count of elements with id username is less than 6. To check the length of the value of name, do the following:
name.val().length < 6
count length on value not on object, change name.length to name.val().length
if (name.val() == "" || name.val().length < 6 ) {
Instead I suggest change here
var name = $("#username").val();
and check like below, there is no need to check for empty, only name.length < 6 is enough
if (name.length < 6 ) {
$(document).ready(function(){
$('#frm').submit(function(){
if(!$('#name').val()){
alert('Please enter your name');
}
else if(!$('#age').val()){
alert('Please enter your age');
}
else if(!$('#mobile').val()){
alert('Please enter your mobile');
}
else if(!$('#email').val()){
alert('Please enter your email');
}
});
});
<html>
<head>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="frm">
<input type="text" name="name" id="name" placeholder="Name..."><br><br>
<input type="number" name="age" id="age" placeholder="Age..."><br><br>
<input type="number" name="mobile" id="mobile" placeholder="Mobile..."><br><br>
<input type="email" name="email" id="email" placeholder="Email..."><br><br>
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>

javascript onsubmit event for multiple functions check doesn't work

In mi validation form I have two input fields in order to write email and confirm it.
Before the submit informations, two confirms are needed:
1-email must seems an email,
2-email one must match the email two.
I can handle these statements each one using two separate javascript functions but i fail when I try to check them all in the onsubmit event attribute. If I write a correct email adress, the form reach the action destination, even if the confirm email doesn't match.
Looking around the web doesn't help me.
Here u are the code (html/javascript):
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Email Validation</title>
<script type="text/javascript">
function isEmail(email, output) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById(email).value;
if (regex.test(email)) {
return true;
} else {
document.getElementById(output).innerHTML = 'wrong email';
return false;
}
}
function compareEmail(email, emailToCompare, output){
var email = document.getElementById(email).value;
var emailToCompare = document.getElementById(emailToCompare).value;
if(emailToCompare == email){
document.getElementById(output).innerHTML = 'ok!';
return true;
}else{
document.getElementById(output).innerHTML = 'emails dont match!';
return false;
}
}
function check(){
return isEmail() && compareEmail();
}
</script>
</head>
<body>
<form action="file.php" method="post" onSubmit="return check()">
<p>Email</p>
<input type="text" name="email" maxlength="50" id="email">
<div id="email_result">
</div>
<br/>
<p>Confirm email</p>
<input type="text" onpaste="return false;" autocomplete="off" name="email" maxlength="50" id="confirm_email" onKeyUp="return compareEmail('email', 'confirm_email', 'confirm_email_result')">
<div id="confirm_email_result">
</div>
<input type="submit" name="submit" value="Register" onclick="return isEmail('email', 'email_result');">
</form>
</body>
The double control doesn't work with the follow script too:
function check(){
if (isEmail() && compareEmail()){
return true;
}else{
return false;
}
}
Nothing changes if I use:
onSubmit="return check()"
or
onSubmit="check()"
in the form event attribute.
You are missing the parameters in the function calls:
function check(){
return isEmail('email', 'email_result') && compareEmail('email', 'confirm_email', 'confirm_email_result');
}
Side note: You have declared variables in the functions with the same name as the parameters. It still works at it is, but the variables are not actually created but will overwrite the parameter values, so the code is a bit confusing.

validate multiple URL input fields

I have following Javascript validation function that should check that the URL posted to my php are OK - if not display a message to correct the entry.
I must have done a mistake somewhere because it is not working and my console.log says: ReferenceError: Can't find variable: $
validateFormbasic.html:12
onsubmitbasic.html:24:95
Could you tell me how to fix it please? Thanks a lot!
<form method="POST" name="inputLinks" onsubmit="return validateForm();">
<input type="text" name="web1" id="url1" placeholder="domain.com">
<input type="text" name="web2" id="url2" placeholder="domain.com">
<input type="text" name="web3" id="url3" placeholder="domain.com">
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
function validateURL(web1, web2, web3) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#url1", "#url2", "#url3").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
}
return false;
}
</script>
As Alberto's comment mentions, it looks like jQuery isn't loaded at the point of calling the function. It also looks to me as if you're syntax for selecting the URL values isn't quite right.
I would use something along the lines of:
<form method="POST" name="inputLinks">
<input type="text" name="web1" id="url1" class="url" placeholder="domain.com" />
<input type="text" name="web2" id="url2" class="url" placeholder="domain.com" />
<input type="text" name="web3" id="url3" class="url" placeholder="domain.com" />
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
$(function(){
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
$('form').submit(function(e){
var isValid = true;
$('.url').each(function(){
isValid = validateURL($(this).val());
return isValid;
});
if (!isValid){
e.preventDefault();
alert("Please enter a valid URL, remember including http://");
}
});
});
</script>
Update
Demo JS Fiddle

How to retrieve the values from an form to another html?

My code is ...
<form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" />
<input type="submit" value="Login"/>
So, when I pressed the Login it will call method validateForm() and returns the boolean
function validateForm()
{
var x=document.forms["myForm"]["StuserID"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
}
Firstly, if the userId is null it should show an alert "Name must be filled out" and return false. In my case, it is succeeding and move to demo_form.html. How can I make it so that form submission and continuing to demo_form.html is only done when function returns true?
Secondly, how do I get the userid in demo_form.html from the form when pressing the login button?
you have to use php file to retrieve data from html form.your html code form should be
<form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" required />
<input type="submit" value="Login"/>
and then
function validateForm()
{
var x=document.getElementById["StuserID"].value;
if (x=="")
{
alert("Name must be filled out");
return false;
}
else
{
return true;
}
}
your should use following code for demo_form.php file
<?php
$user = $_GET['StuserID'];
echo $user;
?>
1) Because false prevent the default behavior of form submit.
2) Create a session and use userid in session variable
I did't got exact error but in my case this following code works you can try this also
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
alert("sdfdfsf");
// return false;
var x=document.forms["myForm"]["StuserID"].value;
if (x==null || x=="")
{
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.html" onsubmit="return validateForm()" method="GET">
<input type="text" name="StuserID" id="basic" value="" placeholder="userID" />
<input type="submit" value="Login"/>
</form>
</body>
</html>
and you can use jquery function also
Like .submit

Categories

Resources