Basic Form Validation with JavaScript/HTML - javascript

I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.

First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.

You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer

The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}

Related

interactive PDF Form-Validation Javascript

I'm trying to validate my interactive PDF. So if i click on a button (for validating) there's following code behind it:
var isBlank = false;
var blank = "Please fill following fields:";
var isNotValid = false;
var notValid = "Please check input data in following fields:";
var message = "";
var t = ['Division', 'Oragnisationseinheit', 'Name', 'KZZ', 'Privataddresse'];
var i;
for(var i=0; i<t.length;i++){
//validation text fields needs to be filled in
if (this.getField(t[i]).value == "") {
blank = blank + "\n" + this.getField(t[i]).name;
isBlank = true;
}
//validation text field must contain only lower case letters
if (/^[a-z]*$/.test(this.getField(t[i]).value) == false) {
notValid = notValid + "\n" + this.getField(t[i]).name;
isNotValid = true;
}
//generate message
if (isBlank == true) {
message = blank + "\n" + "\n";
}
if (isNotValid == true) {
message = message + notValid;
}
}
//check all conditions
if ((isBlank == true) || (isNotValid == true)) {
//show message
app.alert({ cMsg: message, cTitle: "Input data error" });
}
The problem is now, if I press the button there's no reaction. --> the var message wont being displayed. Where is the issue?
Thanks for all ideas.
You might try instead to add a custom validation script that would first check to be sure the field isn't blank and if not, simply change the input to lower case so the user doesn't need to modify the field themselves.
Add the following code to the custom field validate script. This should work for any text field.
if (event.value.length == 0) {
app.alert({ cMsg: event.target.name + " cannot be blank.", cTitle: "Input data error" });
}
else {
event.value = event.value.toLowerCase();
}

Setting a default field value on HTML form if blank

I'm editing Dotmailer's signup form code as some of my users won't have email addresses. I want to set the form so that if the user does not enter a value for their email address, for it to default to say test#test.com
The field must be filled for it to successfully upload for the Dotmailer DB so I can't just remove it as a required field.
Below is the script at the start of the form which seems to be causing the issues (from my limited knowledge)
<script language="javascript">// <![CDATA[
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
var isError = false;
if (errorString.length > 0)
isError = true;
if (isError)
alert(errorString);
return !isError;
}
// ]]></script>
Ty in advance for any assistance you can provide.
You just need to change
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
to
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
var input = document.getElementById('#myInput');
input.value = "test#test.com";
}
where #myInput is the id of the email field.

Is there an easier way to validate my form in jquery rather than what I have??

I am trying to create form validation using jquery. First, the code doesn't work for me and secondly I am hoping there is an easier way to use jquery to validate my form using reg ex patterns. I don't know if I am using jquery corectly and I would like to avoid using any plugins.
$(document).ready(function() {
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var pattern1 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
var pattern2 = /[a-zA-Z]*( [a-zA-Z]*)?/;
$('#submit').on('click', function() {
var valid = true,
errorMessage = "",
if ($('#role').val() == '') {
errorMessage = "please choose a role \n";
valid = false;
}enter code here
if ($('#state').val() == '') {
errorMessage = "please choose a state \n";
valid = false;
}
if ($('#major').val() == '') {
errorMessage = "please provide a major \n";
valid = false;
}
if ($('#degree').val() == '') {
errorMessage = "please provide a degree \n";
valid = false;
}
if ($('#location').val() == '') {
errorMessage = "please choose a location \n";
valid = false;
}
if ($('#gradyear').val() == '') {
errorMessage = "please provide a graduation year \n";
valid = false;
}
if ($('#dept').val() == '') {
errorMessage = "please provide your department \n";
valid = false;
}
if ($('#campadd').val() == '') {
errorMessage += "please enter your address\n";
valid = false;
}
if($('#email').val() !== ""){
if(!pattern.test('#email'.val())){
errorMessage += "email invalid!\n";
valid = false;
}
if($('#telephone').val() !== ""){
if(!pattern1.test('#telephone'.val())){
errorMessage += "telephone number invalid!\n";
valid = false;
}
}}
if( !valid && errorMessage.length > 0){
alert(errorMessage);
}
First, the code formatting in your post is a bit off, which makes it somewhat difficult to read. What exactly do you mean when you say it "doesn't work"?
My best guess is that you mean the form still submits, even after the errorMessage alert box appears. If this is the case, that is probably because you are not canceling the submit event.
Change your code like this:
// submit instead of click event, give a name to the event argument
$('#submit').on('submit', function(e) {
//...
if( !valid && errorMessage.length > 0){
e.preventDefault(); // prevents the form submission
alert(errorMessage);
}

Javascript object is null or not object in IE

I have a form to which a checkbox is added by javascript, when the form is submitted it checks if the checkbox has been ticked or not. This works fine in Firefox or Chrome, but in IE7 or 8 it causes an error document.myform.mycheckbox.checked is null or not an object.
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "mycheckbox";
checkbox.value= 291;
var div = document.getElementById("addcb");
div.appendChild(checkbox);
checkbox.checked = false;
In the form tag I have onSubmit="return CheckForm();", which works ok in Firefox or Chrome, but in IE7 or 8 it submits the form without checking the form or other form objects.
if (document.myform.mycheckbox.checked == false){
errorMsg += "\n\tAgree \t- Please Click I Agree Checkbox";
}
//If there is aproblem with the form then display an error
if ((errorMsg != "") || (errorMsgLong != "")){
msg = "_______________________________________________________________\n\n";
msg += "The form has not been submitted because there are problem(s) with the form.\n";
msg += "Please correct the problem(s) and re-submit the form.\n";
msg += "_______________________________________________________________\n\n";
msg += "The following field(s) need to be corrected: -\n";
errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
return false;
}
return true;
I used the Developer tools to create a Brakpoint which reports the error:
document.myform.mycheckbox.checked is null or not an object
While creating it, give it an ID as well
checkbox.id = "mycheckbox";
and then to find it do a
if (document.getElementById("mycheckbox").checked == false)

replace span text (error) after retyping vars jquery javascript

Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.

Categories

Resources