Checking For Matching Email's In HTML Form - javascript

I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>

With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.

Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.

Related

Javascript form validation return false error

I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.

Regex email validation on submit

I want to do a very basic jQuery validation of an email via a regex on submit. My HTML:
<form action="POST" id="form">
<input type="email" id="customer_email" placeholder="email here" />
<input type="submit" />
</form>
JS:
$('#form').submit(function() {
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').value();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
To my understanding, for this to work I need to get the value of the input via email input (which I do on line 4) and run a regex on it.
When submit is clicked, the standard input error appears on the form, and not the window alert. Feel free to view a Codepen outlining this here:
http://codepen.io/anon/pen/oYmJLW?editors=1010
You need to add event.preventDefault() to prevent the actual form submission, and use .val() instead of .value() on the input.
$('#form').submit(function(event) {
event.preventDefault();
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').val();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
By declaring your input as type="email" your browser will do the validity checking (you don't need to do it yourself then), if you want to circumvent that use type="text".

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Validating form data in Javascript xhtml 1.0 strict, not considering server side scripts for this instance

There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories