I'm trying to make validate if an email form field is not empty, of course I'm learning by making mistakes, but some explanation is needed from any of You Pro guys.
Heres wat I have and it's not working, all do it looks logical to me.
<script>
document.getElementById('regform').addEventListener("submit", function(e))
{
if(document.querySelector("#mail")=='')
{
e.alert("You need to provide a valid email");
}
});
</script>
I'm kind of confused here.
This is the HTML:
<form class="login_form" id="regform" action="" method="post">
<input type="email" name="mail" id="mail" placeholder="Your # email" required>
<input type="submit" value="INGRESAR">
</form>
<script>
document.getElementById('regform').addEventListener("submit", function(e))
{
if(document.querySelector("#mail").value == '')
{
e.alert("You need to provide a valid email");
}
}
</script>
get value from input text using document.querySelector("#mail").value anddocument.querySelector("#mail") only get element
Related
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>
Here is the code;
<form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data">
<div class="css-o5d3v1 e1ovefus2">
<div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3ser1">
<div class="css-gg4vpm e1eu3ser4">
<label for="guestForm-email" id="guestForm-email-label" data-test="input-label" class="css-1k1vx4d e1eu3ser5">Email Address*</label>
</div>
<div class="css-1tpy6sb e1eu3ser7">
<input data-test="guestForm-email" aria-invalid="true" aria-required="true" id="guestForm-email" type="email" name="email" aria-labelledby="guestForm-email-label" class="css-15uq4zo e1eu3ser9" value="" aria-describedby="guestForm-email-error">
</div><span data-test="input-error" id="guestForm-email-error" role="alert" class="css-mf5akt e1eu3ser0">Please enter email address</span></div>
</div>
<button type="submit" data-test="guestForm-submitButton" class="e1ovefus0 css-1wqqz58 e1y6awi20"><span>Continue as Guest</span></button>
I tried doing;
$("#guestForm-email").value = "test#gmail.com"
but when submit it deletes the text in textfield.
I just need to learn how to validate it in JQUERY.
Can anyone help?
Thanks.
Not sure what exactly this has to do with validation, but this is not how you set a value to a form element in jQuery:
$("#guestForm-email").value = "test#gmail.com"
This is:
$("#guestForm-email").val("test#gmail.com")
First of all you cant write this as
$("#guestForm-email").value = "test#gmail.com"
this is the correct syntax
$("#guestForm-email").val("test#gmail.com")
and try to do this in function that return true if the data is valid an call it in
<form onSubmit="return validate()">
I guess what you are trying to do is to validate the e-mail sent on the input text field using jQuery. You can use a reg expression for this within your button's click event handler like so:
$(document).ready(function() {
$("button[type=submit]").click(function() {
if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($("#guestForm-email").value)) {
return $("#guestForm-email").value;
} else {
alert("Invalid E-mail");
}
}
}
I think you want to append text inside input:
$("#guestForm-email").val($("#guestForm-email").val()+"test#gmail.com")
I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.
I'm new here and I'm not an expert of coding, I'm still learning, so be patient please. :)
I created a simple form that is supposed to send an e-mail with a CV attachment. I found the code for this job and it works as intended (sends the mail with file correctly). I didn't use phpmailer or similar, it's just the simple php mail function.
I want a client side validation, javascript/jquery classic, and maybe a server side later. The point is that I can't prevent the form from being submitted to process the javascript validation. I guess it's because there is a file (I used the same form, without attachments, elsewhere and it works pretty well). I post the code so you can see what's wrong:
<form method="post" action="mail.php" id="uploadform" enctype="multipart/form-data">
<p>Name :</p>
<input name="name" id="name" type="text" />
<p>E-mail :</p>
<input name="email" id="email" type="text" />
<p>Tel :</p>
<input name="tel" id="tel" type="text" />
<p>Message :</p>
<textarea name="mex" id="mex" rows="7" cols="10"></textarea>
<p>File Upload :</p>
<input name="file" id="file" type="file">
<input type="submit" name="submit" id="submit" value="send" />
</form>
and this is the script:
<script type="text/javascript">
$(document).ready(function () {
$('#uploadform').submit(function (){
validateForm();
return false;
});
function validateForm(){
var name=document.forms["uploadform"]["name"].value;
if(name==null || name=="") {
$('#name').attr("placeholder","Who is writing?");
return false;
}
var email=document.forms["uploadform"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
$('#email').val("");
$('#email').attr("placeholder", "Insert a valid e-mail address!");
return false;
}
}
});
</script>
I still can't find why the script doesn't prevent the data from being submitted. It seems it ignores the javascript at all. I tried also with different methods, like onsubmit inline on the form tag, event.preventDefault(); and similar, but the behavior is the same. I'm getting crazy for this small issue. I'd be glad if someone could help/explain. Thanks!
You have wrapped your check inside the callback of the submit function.
You should do it like:
$(document).ready(function () {
$('#submit').click(function (event){
return validateForm();
});
function validateForm(){
var name=document.forms["uploadform"]["name"].value;
if(name==null || name=="") {
$('#name').attr("placeholder","Who is writing?");
return false;
}
var email=document.forms["uploadform"]["email"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
$('#email').val("");
$('#email').attr("placeholder", "Insert a valid e-mail address!");
return false;
}
return true;
}
});
Let me know if that works.
I am using a subscribe news letter script by using MySQL and PHP. When the user enters the e-mail and clicks the button the e-mail is added to database.
The issue is that while clicking the button without entering an e-mail, the data base is updating with an empty record. How can I stop submitting the empty fields and force the user to enter an e-mail?
Here is my HTML:
<form id="myForm" action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times New Roman", Times, serif;"/>
<input class="button" type="image" src="rss.png" />
</form>
Sounds to me like you need to do some form validation before you take the user input and insert it into your database. It's dangerous to do as you're doing.
Why not use one of the many plugins out there:
http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins
This is a useful tutorial on using the jquery validation plugin: http://docs.jquery.com/Plugins/Validation
Ignore the styling in their example and focus on the core aspects. In your case, the most useful line is:
<input id="cemail" name="email" size="25" class="required email" />
Roughly, you would need to do something like..
var form = $('#mtForm');
$('input').change(function(){
if($((this).val() == ''){
form.unbind('submit').submit(function(){
return false;
});
}
else{
form.unbind('submit');
}
})
You should change the value attribute of your email field to a placeholder attribute. The onfocus, onwebkitspeechchange and onblur code can be removed from the email input tag.
You can use something like this to check for a blank field if that's the only type of validation you're after (below is written with jQuery).
$(function(){
$('#myForm').submit(function(e){
if ($('#email').val().trim() == "") {
// some sort of notification here
e.preventDefault();
return false;
}
});
});
Ideally, you would validate the form on the client side (javascript/JQuery) as well as the server side (php).
For clarity I will remove the inline code on your input box to get this:
<input type="text" name="email" id="email" value="Enter your email here" />
Note - You may use
placeholder='Enter your email here'
to get the prompt in your input box.
Client side validation using HTML5
Make a required field with email format validation:
<input type="email" name="email" id="email" value="Enter your email here" required="required"/>
Client side validation using javascript/JQuery - example.js
JQuery:
$('#email').bind('blur', function() {
if (!validateEmail($(this).val()) {
// Add errors to form or other logic such as disable submit
}
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test($email);
}
}
Server side validation - update.php
// Require the email
if (empty($_POST['email'])) {
$error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error_message = 'Invalid email format. Example: example#example.example';
} else { // If no errors, continue processing the form
// process the form, enter email
}
The HTML5 alone will prevent submission of the form, however only more recent browsers support HTML5.
Hope this is helpful!