checking object for blank values and show errors - javascript

I am trying to figure out how I can check if any values in the object are blank, and then show the corresponding error.
The form inputs look like this:
<form role="form" action="home.php" class="addLaneForm" id="addLaneForm" name="addLaneForm">
<label for="addlanepartnercode">Partner Code</label><span id="addlanepartnercodeError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnercode" placeholder="Enter Partner Code" />
<label for="addlanepartnername">Partner Name</label><span id="addlanepartnernameError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnername" placeholder="Enter Partner Name" />
<label for="addlaneipicy">IPI/CY</label><span id="addlaneipicyError" class="text-danger laneError" style="display:none;"> * </span>
<select class="form-control validation" id="addlaneipicy">
<option></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
// few more inputs and selects
<button type="button" class="btn btn-default btn-flat addLaneSubmit" id="addLaneSubmit" name="addLaneSubmit">Add</button>
</form>
Here is the onClick event:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let ipiCy = $('#addlaneipicy').val();
let addlane = new ProcessLane();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
ipiCy: ipiCy
}
// how I typically would check the values below:
if(addlanecriteria.partnerCode == ""){
$('#addlanepartnercodeError').show();
return false;
}
if(addlanecriteria.partnerName == ""){
$('#addlanepartnernameError').show();
return false;
}
else{
addlane.addLaneProcessing(addlanecriteria);
}
});
The way I typically check the values is redundant and time consuming.
I did add a class to the inputs called 'laneError'. I was trying to use that to display the errors by calling a function, as follows:
function showAllErrors(){
if($(".addLaneForm .validation") == ""){
$('.laneError').show();
}
}
For one, I wasn't sure where I could put the function call.
But when I was able to call the function, I can only get the first error to show, which is "addlanepartnercodeError".
There has to be a simpler way to check the values in the object.

You can just have a reusable function like below:
showErrorMsg(elemId) {
if($.trim($('#' + elemid).val()) === '') {
$('#' + elemId + 'Error').show()
return true;
}
return false;
}
So your code would just be:-
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let Error = false,
addlane = new ProcessLane();
$('form')
.find("input[id^='add']")
.each((i , e){
if(!Error) {
Error = showErrorMsg($(e).attr('id'))
}
})
if(!Error) {
// Your form has no errors , do your thing here
addlane.addLaneProcessing(addlanecriteria);
}
});

Related

I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)
I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?
Current HTML:
<div class="form-group" id="stage1">
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
</div
I can't use HTML default validation, since I have created a multi-step form.
Thanks in advance,
Brandon
You can iterate through inputs this will assist validating your messy items:
window.onload = () => {
const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
let isAllvaild = true;
allInputs.forEach((element) => {
if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
});
if (isAllvaild) {
afterValidation(); // to keep things clean
}
}
function validateAll(value, type) {
if (type === "text") {
} else if (type === "email") {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let ck = re.test(String(value).toLowerCase());
if (ck) {
// set errors here..
} else {
// maybe remove errors if added previously..
}
return ck;
} else if (type === "phone") {
} else if (type === "other") {
} // add whatever needed..
}
function afterValidation() {
// at this point each input contains valid data.. proceed to next step..
// document.querySelector("#my_id").classList.add("display-block");
// ..
}
you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:
if(textValidation() && emailValidation()){
submit()
}
emailValidation(){
return email ? true : false
}
textValidation(){
return text ? true : false
}
What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?#.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)
function validateInputs ()
{
const inputs = document.querySelectorAll('div[class=row] input');
for (let index = 0; index < inputs.length; index++)
{
const input = inputs[index];
let valid = false;
if (input.value && input.value.trim() !== '')
{
//here you can add specific validations for each id, maybe you can also use switch here
if (input.getAttribute('id') === 'email')
{
//of course, email also need to validate, if dot is present, regular expression might be the best option
if (input.value.indexOf('#') !== -1)
{
valid = true;
}
}
else
{
valid = true;
}
}
if (!valid)
{
input.classList.add('error');
}
else
{
input.classList.remove('error');
}
}
};
window.addEventListener('load', function () {
document.querySelector('button').addEventListener('click', validateInputs)
});
input.error {
background-color: red;
}
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
<button>validate</button>
For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.
Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.
const form = document.querySelector('form');
form.addEventListener('input', event => {
if (form.checkValidity() === false) {
const invalids = form.querySelectorAll(':invalid');
for (const input of invalids) {
console.log(`${input.id} is invalid`);
}
}
});
<form>
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="url" id="website" class="form-control" placeholder="Website*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>
You can use this code between a script tag :
const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });
Or use a Bootstrap classes to validate your form

Delete required on input before submitted in ajax

I tried to validate by submitting a form by using ajax on codeigniter, when I want to insert data but only a few input fields only and input field that I do not use I try to hide, but attr required still running on the input field that I have hidden, how to solve this. so delete the required input field when hidden.
Views
<form id="fr" method="post" class="form-horizontal form-label-left">
<div class="form-group">
<label for="fullname">Section * :</label>
<select name="section" class="form-control" required="required">
<option value="">Select section</option>
<option value="manager">Manager</option>
<option value="head manager">Head Manager</option>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Kitchen * :</label>
<input type="text" name="name_kitchen" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Resto * :</label>
<input type="text" name="name_resto" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="fullname"> </label><br>
<button type="button" id="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
</div>
</form>
<script>
$("[name='section']").change(function(){
var value=$(this).val();
if(value == "manager"){
$("[name='name_kitchen']").hide();
$("[name='name_resto']").show();
}else{
$("[name='name_kitchen']").show();
$("[name='name_resto']").hide();
}
});
$("#submit").click(function() {
$.ajax({
type: "POST",
url: base_url+"add",
dataType: 'json',
data: $('#fr').serialize(),
success: function(data) {
if(data.status) {
$(".add-from-staff").toggle("slow");
$("#fr").load(location.href + " #fr");
$('form#fr input[type="text"],texatrea, select').val('');
}else {
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (request, jqXHR, textStatus, errorThrown) {
alert('Error');
console.log(request.responseText);
}
});
});
</script>
Controllers
public function add() {
$this->_validate();
$insert = $this->My_models->_add();
echo json_encode(array("status" => TRUE));
}
function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('name_kitchen') == '')
{
$data['inputerror'][] = 'name_kitchen';
$data['error_string'][] = 'Kitchen is required';
$data['status'] = FALSE;
}
if($this->input->post('name_resto') == '')
{
$data['inputerror'][] = 'name_resto';
$data['error_string'][] = 'Resto is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
so how when I choose one of the select options that hide disabled required?
when u are hiding any div u can get the element and remove its required attribute using jquery
$("[name='name_kitchen']").removeAttr('required');
e.g:
$("#elementID").removeAttr('required');
In this example I would not use the required attribute. It is causing more headaches than it is worth. Instead, rely on the server-side validation.
To determine which "section" is in use it seems to me that passing another piece of info to the controller would be the easiest way to solve the problem. This could be done many different ways. Adding another hidden field is one option.
Somewhere inside the <form> add
<input type="hidden" id="use-section" name="use_section" value="">
It is not clear that you have a "default" section shown when you first show the page. If there is one then use that for the "value" in the above field.
During the handler
$("[name='section']").change(function(){ ...
set the value of the "use_section" field.
var value=$(this).val();
$("#use-section").val(value);
You can evaluate the "use_section" in your controller, or in your case, in the model which is where I assume you are capturing the data posted.
if($this->input->post('use_section') === "manager")
{
//get the fields you want
}
else
{
//get the other fields
}
I have a suggestion regarding _validate(). Instead of calling exit() to short-circuit add() return a value - TRUE if it works, or $data if it doesn't. The last few lines of _validate() become
if($data['status'] === FALSE)
{
return $data;
}
return TRUE;
Then use this add() method
public function add()
{
if(TRUE === ($status = $this->_validate()))
{
$insert = $this->My_models->_add();
$status = array("status" => TRUE);
}
echo json_encode($status);
}
Use of exit or die in CodeIgniter is, IMO, not appropriate because it short-circuits the framework's designed execution flow.

HTML Form Submit to Google Calendar: Uncaught TypeError, Failed due to illegal value in property: 1

I believe I'm having a similar issue to this problem, but his solution isn't working for me.
I'm trying to have a Google App Script serve an HTML form that adds a Google Calendar event to my calendar.
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function scheduleEvent(array) {
CalendarApp.getDefaultCalendar().createEvent(array[0], array[1], array[2]);
return 1;
}
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="//netdna.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.4/moment-timezone-with-data-2010-2020.min.js"></script>
<style>body{padding:8px}</style>
</head>
<body>
<form class="form">
<fieldset>
<legend>Schedule a Meeting</legend>
<div class="form-group">
<label for="email">Your email:</label>
<input type="email" class="form-control" id="email" placeholder="you#gmail.com" required>
</div>
<div class="form-group">
<label for="eventName">What's the topic?</label>
<input type="text" class="form-control" id="eventName" required>
</div>
<div class="form-group">
<label for="eventLocation">Where?</label>
<input type="text" class="form-control" id="eventLocation" required>
</div>
<div class="form-group">
<label for="startTime">When? (EST)</label>
<input type="datetime-local" class="form-control" id="startTime" required>
</div>
<div class="form-group">
<label for="select">How Long?</label>
<select class="form-control" id="duration" required>
<option value="15">15 Minute Meeting</option>
<option value="30" selected>30 Minute Meeting</option>
<option value="60">60 Minute Meeting</option>
</select>
</div>
<button type="submit" class="btn btn-primary submit" onClick="preprocessForm(this.form)">Submit</button>
</fieldset>
</form>
<script type="text/javascript">
function preprocessForm (form) {
// check if they filled out their email, and set the variable if they did
if (form.email.value) {
var email = form.email.value;
} else {
alert("Please enter your email address, so I know who the appointment is with!");
event.preventDefault();
return 1;
}
// check if they filled out the event name, and set the variable if they did
if (form.eventName.value) {
var eventName = form.eventName.value;
} else {
alert("Please enter a name for the event!");
event.preventDefault();
return 1;
}
// set and format the event time and date, and grab the current time and date
var currentTime = moment().tz('America/New_York');
var startTime = moment(form.startTime.value).tz('America/New_York');
var formattedStartTime = startTime.toDate();
// html5 should stop the user from skipping filling out this section, but check anyway, just in case
if (!form.startTime.value) {
alert("Please enter a time for the event to occur!");
event.preventDefault();
return 1;
}
// we don't want people scheduling meetings in the past
if (startTime.isBefore(currentTime)) {
alert("Please pick a time that is in the future!");
console.log('Start Time: ' + startTime);
console.log('Current Time: ' + currentTime);
event.preventDefault();
return 1;
}
// check if they filled out the event location, and set the variable if they did
if (form.eventLocation.value) {
var eventLocation = form.eventLocation.value;
} else {
alert("Please enter an event location, so I know where to go!");
event.preventDefault();
return 1;
}
// it's not possible to skip the duration, since it's a dropdown that defaults to 30 minutes
var duration = form.duration.value;
var endTime = moment(startTime).add(duration, 'minutes');
var formattedEndTime = endTime.toDate();
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
//toadd: , {location: eventLocation, guests: email}
google.script.run.scheduleEvent(assembledDetails);
// things to try and stop the redirect/refresh when pressing the submit button
event.preventDefault();
return false;
}
</script>
</body>
</html>
I'm not having any luck. On submit, I get this error in the console:
Any advice?
Thanks!
You can't send a date object in the array. Property 1 is the second element in the array: assembledDetails
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
You could change the code to this:
formattedStartTime = formattedStartTime.toDateString();
formattedEndTime = formattedEndTime.toDateString();
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
Then you'd need to convert the date strings back to date objects in the server code.
Or:
You can strigify the object:
assembledDetails = JSON.stringify(assembledDetails);
google.script.run.scheduleEvent(assembledDetails);
And convert the object back in the server:
function scheduleEvent(array) {
array = JSON.parse(array);
Quote from documentation:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.
Apps Script documentation - Parameters and return values

How to compare passwords in Javascript

I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database.
I cannot seem to get it to work.
Any ideas?
function addTodo() {
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) {
alert("Yours passwords do not match");
} else {
curatio.webdb.addTodo(todo.value);
todo.value = "";
alert("Your Registration was successfull");
setTimeout(function () {
window.location.href = "login.html";
}, 1000);
}
}
<div data-role="fieldcontain" >
<label for="todo">
Password
</label>
<input name="" id="todo" placeholder="" value="" type="password" required>
</div>
<div data-role="fieldcontain" >
<label for="todo2">
Retype your Password
</label>
<input name="" id="todo2" placeholder="" value="" type="password" required>
</div>
You're comparing the elements instead of their values.
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) { // Oops
todo and todo2 are 2 different <input> elements.
Try using .value:
if(todo.value !== todo2.value) {
You're comparing the actual elements, which will always be true (because they are both TextFields). Compair their values, like so:
var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;
Either this or change
if(todo != todo2)
to
if(todo.value != todo2.value)
Another way is Object.is(password, confirm_password)

inline javascript form validation

I'm working on a form validation script at work and am having some difficulty. The form is meant to make sure that the user fills out a name, a real-looking email, a category (fromt he drop down) and a question:
This names the form and gathers all the data up from the form:
<script>
function checkForm(form1) {
name = document.getElementById("FieldData0").value;
category = document.getElementById("FieldData3").value;
question = document.getElementById("FieldData1").value;
email = document.getElementById("FieldData2").value;
This checks to see that something is in the "name" field. It works fine and validates exactly like it should, displaying the error text:
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("FieldData0").select();
document.getElementById("FieldData0").focus();
return false;
This also works just like it should. It checks to see if the email field is empty and if it is empty,displays error text and selects that field:
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
This also works just like it should, makes sure that the questions field isn't empty:
else if (question == "") {
hideAllErrors();
document.getElementById("questionError").style.display = "inline";
document.getElementById("FieldData1").select();
document.getElementById("FieldData1").focus();
return false;
}
This one works partially - If no drop down is selected, it will display the error message, but that doesn't stop the form from submitting, it just displays the error text while the form submits:
else if (category == "") {
hideAllErrors();
document.getElementById("categoryError").style.display = "inline";
document.getElementById("FieldData3").select();
document.getElementById("FieldData3").focus();
return false;
}
This one doesn't work at all no matter where I put it. I used a variation on the same script last week and it worked fine. This is supposed to check to see that the email entered looks like a real email address:
else if (!check_email(document.getElementById("FieldData1").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("FieldData2").select();
document.getElementById("FieldData2").focus();
return false;
}
Otherwise it lets the form submit:
return true;
}
This checks the email out:
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
This function hides all errors so the user isn't bombarded with red text. I tried putting in "document.getElementById("emailError").style.display = "none"" but that breaks the whole thing:
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
</script>
And the form looks like this:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<p><div class=error id=nameError>Required: Please enter your name<br/></div><p><strong>Name:</strong> <span></span><br><input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
<label for="name"></label></p>
<p><div class=error id=emailError>Required: Please enter your email address<br/></div>
<div class=error id=nameError2>This doesn't look like a real email address, please check and reenter<br/></div>
<strong><p>Email:</strong> <span>(will not be published)</span><br><input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
<label for="email"></label>
</p>
<div class=error id=categoryError>Please select a category from the drop-down menu<br></div>
<p><strong>Category:</strong> <span></span><br>
<p><select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select><label for="category"></label>
<p><div class=error id=questionError>Please type your question in the box below:<br></div><label for="question"><strong><p>Your Question:</strong> <span></span></label><br>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea></p>
<p><input type="submit" class="btn" value="Submit Question" name="Submit"></p>
</div>
</form>
Is the problem the order that I run the checks? I can't seem to figure this out. Any help would be appreciated.
I've taken the liberty to re-write your javascript to make it more readable and easier to debug.
As Marc Bernier mentioned, the dropdown element does not support the select function so I put an if statement around it to prevent an exception. I've also simplified your checkEmail function, it seemed rather convoluted. I renamed it to isAnInvalidEmail in order to make the checkForm code simpler.
You have also incorrectly named the 'emailError2' div in your HTML, which would cause another exception in the javascript. Your HTML is rather messy and, in some cases, invalid. There are missing quotes on some attribute values and missing end-tags. You should consider using the W3C validator to ensure your HTML is clean and is standards compliant.
I've hosted your code on jsbin: http://jsbin.com/iyeco (editable via http://jsbin.com/iyeco/edit)
Here's the cleaned up Javascript:
function checkForm() {
hideAllErrors();
var formIsValid =
showErrorAndFocusIf('FieldData0', isEmpty, 'nameError')
&& showErrorAndFocusIf('FieldData2', isEmpty, 'emailError')
&& showErrorAndFocusIf('FieldData2', isAnInvalidEmail, 'emailError2')
&& showErrorAndFocusIf('FieldData3', isEmpty, 'categoryError')
&& showErrorAndFocusIf('FieldData1', isEmpty, 'questionError');
/* For debugging, lets prevent the form from submitting. */
if (formIsValid) {
alert("Valid form!");
return false;
}
return formIsValid;
}
function showErrorAndFocusIf(fieldId, predicate, errorId) {
var field = document.getElementById(fieldId);
if (predicate(field)) {
document.getElementById(errorId).style.display = 'inline';
if (field.select) {
field.select();
}
field.focus();
return false;
}
return true;
}
function isEmpty(field) {
return field.value == '';
}
function isAnInvalidEmail(field) {
var email = field.value;
var ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i = 0; i < email.length; i++){
if(ok.indexOf(email.charAt(i)) < 0) {
return true;
}
}
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return re.test(email) || !re_two.test(email);
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("emailError2").style.display = "none"
document.getElementById("categoryError").style.display = "none"
document.getElementById("questionError").style.display = "none"
}
And the cleaned up HTML:
<form onSubmit="return checkForm();" method="post" action="http://www.emailmeform.com/fid.php?formid=303341io4u" name="form1">
<div>
<div class="error" id="nameError">
Required: Please enter your name
</div>
<label for="FieldData0"><strong>Name:</strong></label>
<input type="text" name="FieldData0" id="FieldData0" value="" size="22" tabindex="1" />
</div>
<div>
<div class="error" id="emailError">
Required: Please enter your email address
</div>
<div class="error" id="emailError2">
This doesn't look like a real email address, please check and reenter
</div>
<label for="FieldData2"><strong>Email:</strong>(will not be published)</label>
<input type="text" name="FieldData2" id="FieldData2" value="" size="22" tabindex="2" />
</div>
<div>
<div class="error" id="categoryError">
Please select a category from the drop-down menu
</div>
<label for="FieldData3"><strong>Category:</strong></label>
<select id="FieldData3" name="FieldData3">
<option value="">Please select a category</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="other">Other</option>
</select>
</div>
<div>
<div class="error" id="questionError">
Please type your question in the box below:
</div>
<label for="FieldData1"><strong>Your Question:</strong></label>
<textarea name="FieldData1" id="FieldData1" cols="50" rows="10"></textarea>
</div>
<input type="submit" class="btn" value="Submit Question" name="Submit">
</form>
Regarding the error on the drop-down, don't call this line:
document.getElementById("FieldData1").select();
I seem to recall having the exact same problem a few weeks ago.
First problem: move the content of that if statement into a function...then go from there. You have about 5 pieces of code doing essentially the same thing.
Next: since you're only allowing one error message at a time, create a generic div to hold it and just move the thing. That way, you don't need to keep track of hiding certain errors, displaying others, etc.
Next: only return true or false from your check_email function...returning -1 and false, etc. is bad form even though javascript is lenient on such things.
After you have cleaned up your code, it will be much easier to debug.
I would recommend getting rid of the whole if else chain and check each on individually this this.
var error = 0;
if (value == '') {
error = 1;
// other stuff;
}
if (value2 == '') {
error = 1;
// do stuff;
}
...
if (error) {
// show error
} else {
// submit form
}
Try replacing the == for === which doesn't type cast. It might help you with the dropdown problem.
Your function is returning false and it might also return -1.
As I don't know what type cast JavaScript does with !-1 you should also do this:
check_email(...)!==false;
Instead of this:
!check_email(...)

Categories

Resources