I seem to be unable to get a basic javascript email validation function to work correctly. It keeps returning that the email address is invalid even when using a real email address.
Could someone please point me in the right direction as i couldn't find the problem on any other similar SO posts. I don't think it's the function itself, but perhaps how i am calling it? I have posted the code below.
// E-mail validation via regular expression - taken from SO solution
// Needs to be accessible for other Forms to use
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
// Validate Contact Form
function validate_contact(evt) {
var error = '';
// Set Veriables
var email = document.getElementById("contact_email");
// Validate Other Fields Here
// - Removed for Example -
// Validate Email Address
if (!isValidEmailAddress(email)) {
error += '- Please enter a valid Email Address.\n';
}
// Show Error Notice
if (error != '') {
error = 'The form has not been completed correctly, please check the following:\n\n' + error;
alert(error);
evt.preventDefault(); // Stop the event
} else {
// Proceed
}
}
// Get reference DOM elements
var contact_form = document.getElementById("contact_form");
// Set up event - Contact Form Validation
contact_form.addEventListener("submit", validate_contact);
// Set up event - Other Form Validation
//other_form.addEventListener("submit", validate_other);
<form id="contact_form" method="post" action="" autocomplete="off">
<input type="text" id="contact_email" name="email" value="">
<input type="submit" id="submit">
</form>
You should do some basic debugging. Look at the contents of the variables you are testing.
var email = document.getElementById("contact_email");
The value of email is the input element, not the text entered into it. For that you need to read its .value property.
Solution is to add ".value"
var email = document.getElementById("contact_email").value;
Related
Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:
<div class = mainInfo>
<?php include "header.php"; ?>
<form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
username: <input type = text name = "userName">
password: <input id= "p1" type = password name = "password">
reenter password: <input id ="p2" type = password name = "passwordConfirmation">
<input type="submit" name =" submitButton" value ="submit">
</form>
<div id="feedback">
</div>
</div>
<script>
function validate()
{
document.getElementById("feedback").innerHTML = "functionbeingcalled";
var p1 = document.getElementById("p1").value,
p2 = document.getElementById("p2").value);
if( ! p1===p2 )
{
document.getElementById("feedback").innerHTML = "passwords dont match";
}
if(p1==="")
{
document.getElementById("feedback").innerHTML = "Must have a password";
}
}
window.setInterval(validate(),1000);
</script>
<?php include "footer.php"; ?>
I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all. This line:
document.getElementById("feedback").innerHTML = "functionbeingcalled";
isn't working either.
Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.
Pass the function instead of calling it.
// no parentheses!
window.setInterval(validate, 1000);
And this is wrong.
if( ! p1===p2 )
it should be this
if( p1!==p2 )
because of the higher precedence of the prefix !
I would suggest that you add listeners on your input fields! ;)
It will then only run the validation code when changes are made. In other words; only when necessary.
It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.
I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution
If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution
Well, you've got several issues...
First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.
You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is: if(p1 !== p2 ), which is how you express "not strictly equal to".
Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:
just before the entire form is submitted
just after the user leaves a form field
as the user is entering data
some combination of all 3
Each of those scenarios is handled through event handlers and a working example of each is shown below.
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");
// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");
var form = document.querySelector("form");
// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
// If validate function returns false, don't submit
if(!validate()){
evt.preventDefault(); // cancel the form submission
feedback.textContent = "Can't submit. Form is not valid!";
}
});
// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");
// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);
// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
input.addEventListener("blur", validate); // Used to validate when user moves off of each element
input.addEventListener("input", validate); // Used to validate as data is being entered
});
function validate() {
// Keep track of whether the form is valid or not. Assume that it is by default
var valid = true;
// .innerHTML is for when you want to assign a string containing
// HTML to a DOM element. This invokes the HTML parser and renders
// the HTML. If you don't have HTML in the string, use .textContent
// instead, which doesn't invoke the HTML parser and is more efficient
// See if the password was typed in both boxes before telling the user
// that the passwords don't match
if(p1.value && p2.value){
// Are they the same?
if(p1.value !== p2.value){
feedback.textContent = "passwords dont match";
valid = false;
} else {
feedback.textContent = "passwords match";
}
} else {
// If both password fields aren't filled in, the form can't be valid
valid = false;
}
if(p1.value === "") {
feedback.textContent = "Must have a password";
valid = false;
}
// Send a result to the caller so it can be known by other code if the form is valid
return valid;
}
<div class = "mainInfo">
<form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
<div>username: <input type="text" name="userName"></div>
<div>password: <input id="p1" type="password" name="password"></div>
<div>reenter password: <input id="p2" type="password" name="passwordConfirmation"></div>
<!-- Any form element that has a "name" attribute will submit its name/value as
part of the form data when the form gets submitted. You probably don't want
the actual submit button to be included in this, so don't give the button
a "name" attribute. -->
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<div id="feedback"></div>
</div>
I am working on a contact form.
As the user types in an input field I check the input to see if its valid (with javascript in a function called validateInput()) and a bootstrap popover pops up if it is not valid.
The lastName field and subject field are not required. One question I have, are my regular expressions ok for these?(defined in window.onload)
Anyway, If the user submits the form, further tests are done to see if that data is valid.. (although it was already checked but just in case they ignored the popover).
If the data is indeed valid after pressing submit then the form data is sent to a contact_handler.php through an xmlhttp request.
when arriving there, the post data is checked to see if it is set.. if it is set then i use the filter_var function on the different post data. after that i use preg_replace to filter the names and message field to a limited set of characters.
Then I call a saveContactInfo() function i defined in contact_functions.php which inserts the data to a database.
My question is: Am I doing too much data filtering?.. is there such a thing as doing too much? I just want to make sure the data is safe.
Here is my code. There are lots of comments because it is a college assignment...
contact.html
<form>
<div class="row">
<div class="form-group">
<label for="firstname">Firstname*</label>
<input type="text" class="form-control" id="first-name" maxlength="30" data-trigger="manual" data-placement="top" data-content="Must be at least 3 characters long, and must only contain letters and the following characters .'-" autofocus>
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input type="text" class="form-control" id="last-name" maxlength="30" data-trigger="manual" data-placement="top" data-content="Must only contain letters and the following characters .'-" >
</div>
<div class="form-group">
<label for="email">Email*</label>
<input type="email" class="form-control" id="email" maxlength="254" data-trigger="manual" data-placement="top" data-content="Must be a valid e-mail address.">
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" maxlength="200" data-trigger="manual" data-placement="top" data-content="Must only contain letters, numbers and the following characters .,'-?!="()">
</div>
<div class="form-group">
<label for="message">Message*</label>
<textarea id="message" class="form-control" maxlength="1000" data-trigger="manual" data-placement="top" data-content="A message with a minimum of 15 characters is required. Must only contain letters, numbers and characters such as .,'-?!="()" rows="4"></textarea>
</div>
<div id="form-message" class="form-group">
<p></p>
</div>
<!--give the button an id of submitButton so we can add a click event listener to it in our javascript-->
<button id="submitButton" type="button"class="btn btn-orange"><i class="fa fa-envelope-o"></i> Submit</button>
</div>
</form>
javascript at the bottom of contact.html
<script>
//declare global variables
var firstNameRegex;
var lastNameRegex;
var subjectRegex;
var emailRegex;
var messageRegex;
var xmlhttpContact;
window.onload = function(){
/*this function is implemented after the page is fully loaded.
*the first name field should be a minimum of 3 characters and should only contain letters and certain special characters
*such as full stop, apostrophe, and hyphen.
*/
firstNameRegex = /^([A-Za-z .'-]{3,})$/;
/*The last name field should be a minimum of 0 characters as it is not a required field,
*and should only contain letters and certain special characters such as full stop, apostrophe, and hyphen.
*/
lastNameRegex = /^([A-Za-z .'-]{0,})$/;
/*The subject field is optional so can therefore be a minium of 0 characters.
*If any characters are entered in this field they should only be letters, numbers or certain special characters
*limited to the full stop, apostrophe, and hyphen characters.
*/
subjectRegex = /^([A-Za-z0-9 .,'-?!="()]{0,})$/;
//The email address entered by the user, will be tested against the following regular expression.
//This regular expression for an email address is recommended in the W3C HTML5 specification. (See reference at top of this page.)
emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
//The message entered by the user, will be tested against the following regular expression.
//There is a minimum of 15 characters required in the message.
messageRegex = /^([A-Za-z0-9 .,'-?!="()]{15,})$/;
//add a 'click' event listener to our submit button. When the button is pressed we will call the subitForm() function
document.getElementById('submitButton').addEventListener('click', submitForm, false);
//call the validateInput() function which we have defined below and pass the id of the input fields and their corresponding
//regular expression values as parameters.
validateInput('first-name', firstNameRegex);
validateInput('last-name', lastNameRegex);
validateInput('subject', subjectRegex);
validateInput('email', emailRegex);
validateInput('message', messageRegex);
//remove the form error and success messages when 'keypress' or 'focus' events occur on input or textarea fields.
removeFormMessages();
}
function validateInput(inputID, regularExpression){
/*This is a function which takes in the id of an input field or textarea and a regular expression as parameters.
*In this function we test the value of the input field (or textarea) against the regular expression
*which we have defined for that input type to make sure the input is valid.
*For example if we are taking in the users 'first name' as input, then we will test this against the
*regular expression we have defined for a valid first name (in the indow.onload function).
*If it is NOT valid then we display a popover message to the user.
*If input IS valid then we hide the popover. This gives immediate feedback to the user during the process of filling
*out the form.
*/
//we listen for the following events on the input field or textarea that was passed as a parameter.
//'keyup', 'keypress', 'blur', 'change'
//The input entered in that field is checked for validity when these events occur.
//If it is not valid, then the popover with error message is displayed until input is validated.
$('#' + inputID).on('keyup keypress blur change', function(){
//store the value of our input field into a javascript variable called inputValue
var inputValue = document.getElementById(inputID).value;
//Now we test our inputValue against the appropriate regular expression (which we took in as a parameter).
//the javascript test() function which we use here will return true if the input matches the regular expression
//and false if not.
//We store the boolean result into the variable isInputValid
var isInputValid = regularExpression.test(inputValue);
if(!isInputValid){
//If input is not valid go here
if(!$(this).hasClass('isShowing')){
//if our popover error does not have class isShowing then do the following
//show popover and add class isShowing to the element so that we know what state it is in.
$(this).popover('show');
$(this).addClass('isShowing');
}
//else if our popover error is already showing then leave it showing (ie do nothing here).
}else{
//If input is valid go here
if($(this).hasClass('isShowing')){
//if our popover error has class isShowing then do the following
//hide popover and remove isShowing class so we know it is hidden now
$(this).popover('hide');
$(this).removeClass('isShowing');
}
//else if our popover error is already hidden then leave it hidden.
}
});
}
function removeFormMessages(){
/*This function listens for a 'keypress' or a 'focus' event on input and textarea fields
*and when it detects these events it hides the form-message paragraph.
*We do this because, If a user has submitted the form and then been notified that the 'form is invalid'
*and goes back to change his/her input then we assume they have seen the error message
*so we delete it so that the next time they are notified of something it will be easier to see.
*/
$('input, textarea').on('keypress focus', function(){
$("#form-message p").hide();
$("#form-message p").removeClass('animated').removeClass('bounce');
$("#form-message p").html('');
});
}
function hideAllPopovers(){
/*this function hides all popovers that are currently showing on input fields or textareas.
*We will call this function after the form is submitted, if all fields are valid.
*/
$('input, textarea').popover('hide');
$('input, textarea').removeClass('isShowing');
}
function submitForm(){
//get the values of all input and textarea fields in the contact form
var firstName = document.getElementById('first-name').value;
var lastName = document.getElementById('last-name').value;
var email = document.getElementById('email').value;
var subject = document.getElementById('subject').value;
var message = document.getElementById('message').value;
//we need to check the validity of the input values in case the user has ignored our popover error messages
//therefore test (again) the values the user entered against regular expressions which we defined earlier for different types of input.
//and store the boolean results into variables.
var isfirstNameValid = firstNameRegex.test(firstName);
var islastNameValid = lastNameRegex.test(lastName);
var isSubjectValid = subjectRegex.test(subject);
var isEmailValid = emailRegex.test(email);
var isMessageValid = messageRegex.test(message);
if((!isfirstNameValid) || (!islastNameValid) ||(!isEmailValid) ||(!isSubjectValid) || (!isMessageValid)){
//If any of the values entered to the input fields are invalid then show an error message to the user.
//And do not allow the form to be submitted
//We use the error-text class for red text.
$("#form-message p").html('<span class="error-text"><i class="fa fa-exclamation-triangle"></i> The form is not valid!</span>');
$("#form-message p").show();
$("#form-message p").addClass('animated').addClass('bounce');
}else{
//If form input is valid then firstly hide any popovers which are showing
hideAllPopovers();
//then we create a new xmlhttp request.
xmlhttpContact = createXHR();
xmlhttpContact.onreadystatechange = contactCallback; //when the response comes back call the contactCallback function
//Send our form values to the contact_handler.php page by POST
xmlhttpContact.open("POST", "contact_handler.php" ,true);
xmlhttpContact.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//send our variables to the contact_handler.php page by POST
xmlhttpContact.send("firstName=" + firstName + "&lastName=" + lastName + "&email=" + email + "&subject=" + subject + "&message=" + message);
}
}
function contactCallback(){
//this function will be called when we receive a response back from the xmlhttp request.
if(xmlhttpContact.readyState == 4 && xmlhttpContact.status == 200){
//store the response text into a variable called message.
var message = xmlhttpContact.responseText;
//clear any text in the input fields.
$('input, textarea').val('');
//insert our message to the form-message paragraph tag
$("#form-message p").html('<i class="fa fa-check"></i> ' + message);
$("#form-message p").show();
//we use the bootstrap animation classes to create an animation on the message text.
$("#form-message p").addClass('animated').addClass('bounce');
}
}
</script>
contact_handler.php
<?php
//check if all the required fields are set
if(isset($_POST['firstName']) && isset($_POST['email']) && isset($_POST['message'])){
//collect the post data if the contact form has been submitted and store it into local variables
//Remove all HTML tags from $_POST["firstName"] and store it into variable $firstName
$firstName = filter_var($_POST["firstName"], FILTER_SANITIZE_STRING);
if(isset($_POST['lastName'])){
//check if lastName isset before filtering it.
//Remove all HTML tags from $_POST["lastName"] and store it into variable $lastName
$lastName = filter_var($_POST["lastName"], FILTER_SANITIZE_STRING);
}
//Remove illegal characters from $_POST["email"]
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if(isset($_POST['subject'])){
//check if subject isset before filtering it.
//Remove all HTML tags from $_POST["subject"] and store it into variable $subject
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
}
//Remove all HTML tags from $_POST["message"] and store it into variable $message
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
//do further filtering with preg_replace for extra security.
$firstName = preg_replace("#[^A-Za-z .'-]#i", "", $firstName); //filter everything but letters and a few special characters.
$lastName = preg_replace("#[^A-Za-z .'-]#i", "", $lastName); //filter everything but letters and a few special characters.
$subject = preg_replace("#[^A-Za-z0-9 .,'-?!=\"()]#i", "", $subject); //filter everything but numbers, letters and a few special characters.
$message = preg_replace("#[^A-Za-z0-9 .,'-?!=\"()]#i", "", $message); //filter everything but numbers, letters and a few special characters.
//store the boolean result of saveContactInfo function into a variable called $messageSent
$messageSent = saveContactInfo($firstName, $lastName, $email, $subject, $message, $pdoConnection);//this method is defined in contact_functions.php
if($messageSent){
//if saveContactInfo returns true then we know the data has been entered to the database so we inform the user that
//the message has been sent. This message will be echoed back to our ajax callback method in contact.html
//where we will insert it to the HTML.
echo 'Your Message has been sent!!';
}
}
?>
contact_functions.php
<?php
function saveContactInfo($firstName, $lastName, $email, $subject, $message, $pdoConnection){
$messageTime = time(); //Get timestamp of current time and store it into a variable
try{
$query ="INSERT INTO contact_info (firstName, lastName, email, subject, message, messageTime) VALUES (:firstName, :lastName, :email, :subject, :message, :messageTime)";
$statement = $pdoConnection->prepare($query);
$statement->bindValue(':firstName', $firstName, PDO::PARAM_STR);
$statement->bindValue(':lastName', $lastName, PDO::PARAM_STR);
$statement->bindValue(':email', $email, PDO::PARAM_STR);
$statement->bindValue(':subject', $subject, PDO::PARAM_STR);
$statement->bindValue(':message', $message, PDO::PARAM_STR);
$statement->bindValue(':messageTime', $messageTime, PDO::PARAM_STR);
$statement->execute();
return true;
}catch(PDOException $e){
//throw new pdoDbException($e);
return "Error message " . $e->getMessage();
}
}
?>
is there such a thing as doing too much?
Certainly yes, anything can be done an absurd amount of times to become "too much."
Am I doing too much data filtering?
I would say yes but, the question is pretty vacuous. I'll interpret this to mean 'am I doing the most meaningful validation?". You are doing too much validation because you are validating in the front and the back end. For something that's just going to be on a query-string to contact_handler.php you might just want to do everything in the back-end because anyone can bypass your javascript and type in the query string by hand.
That doesn't wholly mean not to validate on the front end. In practice I usually only do one type of validation on the front end to make sure all the form's fields are filled in.
All the validation for length and content I do on the back end, sending back any errors in the response to the xhr request. Of course re-validating the presence of fields in the query-string is a must as anybody could send a request with an unexpected query-string by hand.
I avoid front-end validation until after the back-end is rock solid.
so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.
<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)