javascript validation works for one value only - javascript

I am trying to validate two input fields in my form using javascript. But my functions checks only one value for null or empty string. It submits the form if the other value is empty. Why?
function checkFieldEmpty()
{
var a=document.forms["verifyURN"]["urnNumber"].value;
var b=document.forms["verifyURN"]["urnDate"].value;
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
return false;
}
return true; //function returns true even if a is empty..?
}
//Below function is called when submit button pressed in my form
function verifyURN()
{
if(checkFieldEmpty())
{
document.verifyURN.rDoAction.value = "<%=Constant.myPage%>";
document.verifyURN.submit();
}
else{
alert("Mandatory fields empty");
return false;
}
}
...
<form name="verifyURN"...

try add
alert(a.length);
alert(b.length);
before your
if (a==null || a=="", b==null || b=="") //b field validates here, not a..?
{
and you will have a better picture of what criteria to check.

Related

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

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.

compressing validation tactics

The following validation code was handed to me and it just looks so repetative. How could I learn from his example on how to reduce the duplicate processes that occur for each input field that is being validated below....? I want to be more efficient with JavaScript, not repeat the same functions over and over again just because a form adds on a new input element...
function isRequired(){
firstNameRequired();
lastNameRequired();
stateRequired();
gradYearRequired();
relationshipRequired();
birthdayRequired();
}
function firstNameRequired(){
var firstName = document.forms['subscribeForm']['First Name'].value;
if (firstName == null || firstName ==''){
alert('Please enter your first name.');
document.subscribeForm.elements['First Name'].style.backgroundColor='yellow';
return false;
}
}
function lastNameRequired(){
var lastName = document.forms['subscribeForm']['Last Name'].value;
if (lastName == null || lastName ==''){
alert('Please enter your last name.');
document.subscribeForm.elements['Last Name'].style.backgroundColor='yellow';
return false;
}
}
function stateRequired(){
var state = document.forms['subscribeForm']['State'].value;
if (state == null || state ==''){
alert('Please enter your state of residence.');
document.subscribeForm.elements['State'].style.backgroundColor='yellow';
return false;
}
}
function gradYearRequired(){
var gradYear = document.forms['subscribeForm']['Graduation Year'].value;
if (gradYear == null || gradYear ==''){
alert('Please enter your graduation year.');
document.subscribeForm.elements['Graduation Year'].style.backgroundColor='yellow';
return false;
}
}
function relationshipRequired(){
var relationship = document.forms['subscribeForm']['ABC Link Relationship'].value;
if(relationship == null || relationship == ''){
alert('Please enter your relationship to ABC.');
document.subscribeForm.elements['ABC Link Relationship'].style.backgroundColor='yellow';
return false;
}
}
function birthdayRequired(){
var birthDay = document.forms['subscribeForm']['Birthdate'].value;
if(birthDay == null || birthDay == ''){
alert('Please enter your birthday.');
document.subscribeForm.elements['Birthdate'].style.backgroundColor='yellow';
return false;
}
}
...
<input type="submit" class="submitBtn" value="" onclick="isRequired()" />
Also, I have the flexibility to work in jQuery if need be.
Detect what parts in your code are repetitive and what parts do change from field to field. For example, you could create a function that takes two parameters: the field name and its label.
function validateRequiredField(name, label)
{
var value = document.forms['subscribeForm'][name].value;
if (value == null || value == '') {
alert('Please enter your ' + label);
document.forms['subscribeForm'][name].style.backgroundColor = 'yellow';
return false;
}
}
Then you can just call this function passing the name and the label as parameter:
validateRequiredField('First Name', 'first name');
validateRequiredField('ABC Link Relationship', 'relationship to ABC');
// ...
Keep in mind that these validations should be done also in server side, because someone can just disable JavaScript and send your form skipping your client side validation functions.
Because the only data being passed is the object and the alert message, instead of a whole custom function, use a single function with object and message params.
function isRequired(){
required(document.forms['subscribeForm']['First Name'],'first name');
required(document.forms['subscribeForm']['Last Name'],'last name');
required(document.forms['subscribeForm']['State'],'state of residence');
required(document.forms['subscribeForm']['Graduation Year'],'graduation year');
required(document.forms['subscribeForm']['ABC Link Relationship'],'relationship to ABC');
required(document.forms['subscribeForm']['Birthday'],'birthday');
}
function required(object,message){
if (!obj) {
alert('Please enter your '+message);
obj.style.backgroundColor='yellow';
return false;
}
return true;
}
First of all I would recommend to use IDs to read out the form fields:
<input type="text" id="firstname" />
This allows you to use jQuery('#firstname') to select this input field.
Second, here's how I'd go about the task of making the code smaller:
What are you trying to do here?
You always read some value from the form (depending on an ID of sorts).
Then you check if that value is null.
If the value is not set you want to display an error message (depending on the ID again).
And you also want to mark the field that was missing and then return false.
So I'd code a function that does exactly that:
// function having a parameter for the ID and the custom error message
function checkFormField(fieldID, errorMsg) {
// read value from field using jquery
value = $(fieldID).value();
// check for null or empty
if (value == null || value == '') {
// display custom error message
alert(errorMsg);
// change color of field using jQuery
$(fieldID).css('background', 'yellow');
return false;
}
}
Now you can reuse this function for every field you want to check. The new isRequired method would look like this:
function isRequired(){
checkFormField('#firstname', 'Please enter your first name.');
checkFormField('#lastname', 'Please enter your last name.');
// and so on...
}
Note that this example would require name attributes that can be used as identifiers (no spaces)
<input name="first_name" type="text" />
<input name="last_name" type="text" />
js:
function validateRequired(slug, field){
// test for passing condition
if (field.value !== null && field.value !== '') {
return true;
}
else {
alert('Please enter your ' + field.str);
}
return false;
}
/**
* Validate a form using a ruleset object
*
*/
function validateFields(ruleset, form){
var field = {};
var errors = 0;
// Loop though the ruleset
for(var index in ruleset) {
//
if (ruleset.hasOwnProperty(index)) {
field = ruleset[index];
// check if input exists
if (form[index]){
field.value = form[index].value
}
if (ruleset[index].required) {
if (!validateRequired(field)){
errors++;
field.invalid = true;
}
}
// you could add more rules here...
}
}
return errors === 0;
}
var valid = validateFields({
first_name : {
required : true,
str: 'first name'
},
last_name : {
required : true,
str: 'last name'
}
// ...
}, document.forms['subscribeForm']);

Javascript, alert if a value on $(reviewForm).serialize() is blank?

I'm submitting a form with JS and I want to cancel the submit if any field is blank.
I'm getting all values with: $(reviewForm).serialize()
which returns something like:
id=2&text=aaaa&rating=2&gender=
How can I show an alert if any value in the form is blank?
var serialized = $(reviewForm).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){
//you've got empty values
}
using jQuery, you can test it before serializing:
$(reviewForm).find('input').each(function(idx, elem){
if($(elem).val().length == 0){
//this field is empty
}
});
Before submitting the form you can do something like this.
if($(reviewForm).find('input, select, textarea').filter(function(){
return $(this).val() == '';
}).length > 0){
alert('Enter all the values');
}
else{
//Submit the form here
}
This will check for empty fields, return array of the field names, and alert how many fields are empty. check the fiddle for a demo: http://jsfiddle.net/brentmn/Pwngn/
$('form').submit(function(){
var s = $(this).serialize();
var empty = $.grep(s.split('&'), function(field){
//get empty fields
return field.split('=')[1] === '';
}).map(function(arr){
//return field name of empty field
return arr.split('=')[0];
});
alert(empty.length + ' empty fields');
return !empty.length;
});

JavaScript code returns false, but still the form is submittted

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?
Button code:
<input type="submit" name="button" id="button"
onclick='return formvalidation();' value="Next" />
Non-working function example:
function BlankSite() {
var SiteNum= document.getElementsByName("sitesinput")[0].value;
if ((SiteNum == "") || (SiteNum == 0))
{
alert("You have not selected an amount of sites.")
document.forms[0].button.disabled = true;
return false;
}
}
Function initiator:
function formvalidation()
{
ZeroPhones();
BlankPC();
BlankSite();
BlankSeats();
phone_change();
} // End of formvalidation
This is very strange and I have tried various workarounds all to no avail!
You need to have return false; in the function called by the onclick, in this case formvalidation.
Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.
They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:
function formvalidation(){
{
if (!ZeroPhones())
return false;
if (!BlankPC())
return false;
//
// keep checking for false and return false.
//
// default to return true
return true;
}
So when the functions do in-fact return false, the false return is carried back up through to the bound function.
BlankPC() is called by formvalidation so false is returned into the method formvalidation().
Your formvalidation() is always falling off the end which is the same as returning true.
If you want it to return false when one of your validations fails, it should be:
function formvalidation()
{
retval = true;
retval &= ZeroPhones();
retval &= BlankPC();
retval &= BlankSite();
retval &= BlankSeats();
retval &= phone_change();
return retval;
} // End
This can be optimized a bunch, but you can get the gist of it.
Call the JavaScript function onSubmit of the form instead of calling at button onClick.
JavaScript code
function validate()
{
alert('test');
return false;
}
<form action="test" method="post" onsubmit="return validate();">
This is working fine for me.
formvalidation() isn't returning false.
Maybe you want something like:
function formvalidation()
{
if(!ZeroPhones() ||
!BlankPC() ||
!BlankSite() ||
!BlankSeats() ||
!phone_change())
return false;
}
My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:
function checkPassword() {
// This is my submit button
document.getElementById('nextBtn').setAttribute('disabled', 'disabled');
password1 = document.getElementsByName("pwd1")[0].value;
password2 = document.getElementsByName("pwd2")[0].value;
if (password1 == '') {
// If password not entered
alert ("Please enter Password");
return false;
} else if (password2 == ''){
// If confirmation password not entered
alert ("Please enter confirm password");
return false;
} else if (password1 != password2) {
// If NOT the same, return false.
alert ("\nPassword did not match: Please try again...");
return false;
} else {
document.getElementById('nextBtn').removeAttribute('disabled');
return true;
}
}

Categories

Resources