Having difficulty getting Javascript form to validate - javascript

Been looking for an answer for hours now and I still haven't come up with a solution. I've tried looking for similar question, but none have helped, really.
So basically, what doesn't work is that the form submits without any error messages even if there are mistakes on the form. Basically, I could leave the name field empty and the form will still submit once I press the button. Hope this made sense. Any help is appreciated
Code:
function validateFinale()
{
var emailOne = document.getElementById("em1").value;
var emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
if (compare())
{
if (name, 'Please enter name'))
{
if (validEmail(getElementById('em1'), 'Email invalid'))
{
}
}
}
return false;
}
function validName(elem, helpmsg) {
if (elem.value.length == 0) {
alert(helpmsg);
return false;
} else {
return true;
}
}
function validEmail(elem, msg) {
var wrongem = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]+$/;
if (elem.value.match(wrongem)) {
return true;
} else {
alert(msg);
return false;
}
}
function compare() {
if (emailOne != emailTwo) {
alert("Emails not the same");
submitOk = "false";
Document.getElementById("em1").value = " ";
Document.getElementById("em2").value = " ";
Document.getElementById("em1").focus();
} else {
alert("form complete, thank you");
}
}
http://jsfiddle.net/aj240/qgmt5yr8/

you made syntax mistake, first you declare emailOne as local variable, than try reach it in global scope. You should declare variables emailOne and emailTwo in global scope.
var emailOne;
var emailTwo;
function validateFinale()
{
emailOne = document.getElementById("em1").value;
emailTwo = document.getElementById("em2").value;
var name = document.getElementById("name1").value;
One gold tip, try press F12 in your browser and all errors messages would appear in console.

Try setting required ="true" in the input elems:
<input type="text" required ="true"...
Also, if you set type="email" in the e-mail field it will ask for an e-mail address (not at all, though, it just will accept anything with an "#")
And the code validName(getElementById('name1'), ...) should be validName(getElementById('name1').value, ...), or else you'll get all the HTML element

Related

How to return a light box error message from a function

I've created a basic form validation script that I want to return an error messages as a light box, rather than using an alert() message. I like the look of featherlight.js, but I can't figure out how to return it from a function? Any other suggestions would be greatly appropriated. Thanks in advance.
The featherlight.js repo
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
alert('Please enter your first name');
return false;
}
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>
I know this is a bit late, but I think I know what you're after. I've just done a similar thing myself, so I'll put it here incase it helps anyone.
I created a function so you can re-use it elsewhere along with an OK button to close the light box.
function customAlert(message = '') {
var alertBox = $(document.createElement('div'));
alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
$.featherlight(alertBox);
}
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
customAlert('Please enter your first name');
return false;
}
}
Basically, you cannot "return" it. What you can do is you can trigger a lightbox event when your conditions are match, like this:
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
$.featherlight($content, $configuration); // Lightbox for wrong validation
return false;
} else {
$.featherlight($content, $configuration); // Lightbox for successful validation
return true;
}
}
And of course, you will need to modify $content and $configuration variables as you want as explained here:
https://github.com/noelboss/featherlight/

loop through all fields and return false if validation of any one field fails jquery

I am facing big trouble resetting the flag variables. I am not sure where I am missing :(
I have a form with lots of text fields. I am trying to loop through all the fields and on blur of each of the field I am doing some validations. If any of the validation for any of the field fails it should not submit the form. But now I am having a big trouble doing this. If I have 3 fields and the first value I have entered wrong and next two fields if I have given correct, its submitting the form which should not be. Can somebody please help me in this?
var globalValid = false;
var validators = {
spacevalidation: function(val) {
if($.trim(val) != "")
return true;
else
return false;
},
//Other validation fns
};
$('#form1 .required').blur(function(){
var input = $(this);
var tmpValid = true;
input.each(function(){
var classReturn = true;
validatorFlag = true;
input.next('ul.innererrormessages').remove();
input.removeClass('required_IE');
if(firstTime)
{
input.addClass('valid');
}
if (!input.val()) {
input.removeClass('valid');
input.addClass('required');
var $msg = $(this).attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
globalValid = false;
}
else{
if(this.className) {
var classes = this.className.split(/\s+/);
for(var p in classes) {
if(classes[p] in validators) {
tmpValid = (tmpValid && validators[classes[p]] (input.val())) ? tmpValid : false;
}
}
}
if(tmpValid == false){
input.removeClass('valid');
input.addClass('required');
var $msg = input.attr('title');
input.after('<ul class="innererrormessages"><li>'+$msg+'</li></ul>');
}
}
});
globalValid = tmpValid;
});
$('#form1').submit(function() {
var returnValue = true;
if(globalValid )
{
returnValue = true;
}
else{
returnValue = false;
}
alert("returnValue "+returnValue);
return returnValue;
});
Using this code, if I put a wrong value for first field and correct value for the other two fields, ideally it should return false. But its returning true. I think I am not properly resetting the flag properly
Checkout this example which provides the basic premise of what needs to occur. Each time the blur event is fired you must validate all three fields and store the result of their validation to a global variable.
HTML
<form>
<input />
<input />
<input />
<button type="submit">Submit</form>
</form>
Javascript
var globalValid = false; //Global validation flag
$("input").blur(function(){
//local validation flag
var tmpValid = true;
//When one input blurs validate all of them
$("input").each(function(){
//notice this conditional will shortcircuit if tmpValid is false
//this retains the state of the last validation check
//really simple validation here, required value less than 10
tmpValid = (tmpValid && this.value && this.value < 10) ? tmpValid:false;
});
//assign the result of validating all inputs to a global
globalValid = tmpValid;
});
$("form").submit(function(e){
//This is just here to make the fiddle work better
e.preventDefault();
//check the global validation flag when submitting
if(globalValid){
alert("submitted");
}else{
alert("submit prevented");
}
});
JS Fiddle: http://jsfiddle.net/uC3mW/1/
Hopefully you can apply the principles in this example to your code. The main difference is the code you have provided does not validate each input on blur.

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

JS validation issue

My validation function looks like that.
var fname = $("#fname").val();
var lname = $("#lname").val();
function validate() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid=false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid=false;
}
It simply changes the class of unfilled input box.
I know that i can write else for every if and change back to default (class="valid") if user fills some of inputs. But how can i create something universal for all inputs to change back to default class the input that user has filled after first validation error?
That was good Tural! HOWEVER, why the excess processing in your code? That will add unecessary stress. Since you, for what you "solved", will add the "valid" class to ALL the input type text or password, just add that to the actual input element in the straight code:
<input class='valid' ..... />
Now, back to your original validation: why not make it universal?:
function validate(formField) {
if !formField $('#'+formField).removeClass('valid').addClass('invalid');
}
Or something in that vein ...
You can either assume everything is valid and then try to disprove that or you can try to prove its validity. The below takes the first approach and sets all the classes to "valid" to be consistent with that.
function validate() {
// Get the current form input state.
var fname = $("#fname");
var lname = $("#lname");
// Assume everything valid until proven otherwise.
var isValid = true;
fname.attr('class', 'valid');
lname.attr('class', 'valid');
if (!fname.val()) {
fname.attr('class', 'invalid');
isValid=false;
}
if (!lname.val()) {
lname.attr('class', 'invalid');
isValid=false;
}
return isValid;
}
Ok. I found the way
$('input[type="text"],input[type="password"]').keypress(function () {
$(this).attr('class', 'valid');
});

[JavaScript]: How to define a variable as object type?

I am using following code to check whether a check box on my website page is checked or not. But there are several check boxes and I want to use this same function. I want to call this function from a Submit button click and pass the check box name as argument. It should than validate that check box.
function CheckTermsAcceptance()
{
try
{
if (!document.getElementById('chkStudent').checked)
alert("You need to accept the terms by checking the box.")
return false;
}
catch(err)
{
alert(err.description);
}
}
Just pass a parameter to CheckTermsAcceptance(). You also missed a brace after the alert -- there are two statements in that if block, and you'll always execute the return false without it.
function CheckTermsAcceptance(checkboxName)
{
try
{
if (!document.getElementById(checkboxName).checked) {
alert("You need to accept the terms by checking the box.")
return false;
}
}
catch(err)
{
alert(err.description);
}
}
To call this from your submit button, have a function like validateForm that's called on submit. Then simply construct a list of the checkboxes and pass in their IDs to CheckTermsAcceptance.
Note that this sort of validation is handled very smoothly by jQuery and its ilk. For example, here's the jQuery validation plugin.
function CheckTermsAcceptance(element){
try{
if (!element.checked){
alert("You need to accept the terms by checking the box.")
return false;
}
}catch(err){
alert(err.description);
}
}
and you call it like:
CheckTermsAcceptance(document.getElementById('chkStudent'));
is that it?
Sorry for not answering your questions. But you should seriously consider using jQuery and jQuery validate.
You could also use more arguments to allow for different options as well.
function CheckTermsAcceptance()
{
var ctrl = arguments[0];
var valueExpected = arguments[1];
var outputMessage = arguments[2];
if(valueExpected == null) valueExpected = true;
if(outputMessage == null) outputMessage = "You need to accept the terms by checking the box.";
try
{
if(ctrl.checked == valueExpected)
{
Log.Message(outputMessage);
}
}
catch(err)
{
alert(err.description);
}
}
this function will work with a bit of fix up, pass argument and make sure you do both the alert and the return false in the if statement
function CheckTermsAcceptance(checkBox) //added argument
{
try
{
if (!checkBox.checked) { //added block to group alert and fail case
alert("You need to accept the terms by checking the box.")
return false;
}
return true; //added success case
}
catch(err)
{
alert(err.description);
}
}
once you have this in place you can then use it on your form validation like so
<form id="formid" action="" onsubmit="return validate('formid');">
<input type=checkbox name="name" id="name"><label for="name">Name</label>
<input type=checkbox name="name2" id="name2"><label for="name2">Name2</label>
<input type=submit>
</form>
<script>
function validate(formid) {
var form = document.getElementById(formid);
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.type == 'checkbox' && !CheckTermsAcceptance(elem)) {
return false;
}
}
return true;
}
</script>
i can confirm that this works in firefox 3.5
also jQuery and jQuery.validate make this very easy to implement in a very declarative way.

Categories

Resources