onsubmit verify that all functions return true - javascript

i have about 6 form inputs that i have javascript running validation on, how would i go about verifying that all functions return as true? here are two samples of my javascript functions
$(document).ready(function() {
//First Name Input Field
$( "#first_name" ).focusout(function() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("First Name* is required so my response won't go to spam");
return false;
} else {
var re = /^[A-Za-z-]+$/;
if(re.test(document.getElementById("first_name").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("First Name* not a valid name");
return false;
}
}
});
//Last Name Input Field
$( "#last_name" ).focusout(function() {
if( this.value === "" || this.value === null ) {
$( "#error_messages" ).text("Last Name* is required so my response won't go to spam");
return false;
} else {
var re = /^[A-Za-z-]+$/;
if(re.test(document.getElementById("last_name").value)) {
$( "#error_messages" ).text("");
return true;
} else {
$( "#error_messages" ).text("Last Name* not a valid name");
return false;
}
}
});
});

Add default variables and set as true.
And when error occurred overwrite the value as false.
Idea is that:
$(document).ready(function() {
var firstnameStatus = true;
var lastnameStatus = true;
if(firstname have error){
// your code
var firstnameStatus = false;
}
if(lastname have error){
// your code
var lastnameStatus = false;
}
if( firstnameStatus == true && lastnameStatus == true){
alert('all fields true');
}
});

Related

Boolean value doesnt change

My JS code:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
});
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
I don't actually understand why my code is not working.
If my <input> is not empty I have to get alert ('ok'), but I don't get anything.
Why my boolean value is still false at the end?
Because it's a callback function, which executes only after the blur function is complete. This means that this line if (name_valid === true) is executing before this line if ($(this).val() != "").
Try changing your code to this:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
You made a little mistake, you should put your last if statement inside callback function, like below:
var name_valid = false;
$("#InputName").blur(function () {
if ($(this).val() !== "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
Your conditional only runs on page load. You want it inside the event handler so it runs when the event actually gets triggered
var name_valid = false;
$("#InputName").blur(function() {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() !== ""){
name_valid = true;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
Please try this.
$(document).ready(function () {
var name_valid;
$("input").blur(function () {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid) {
alert('ok');
}
});
});

How to validate multi-functions using Javascript in .asp

I am attempting to validate 6 functions on a form. I am getting the appropriate alerts set for each function but the form does not seem to be validating correctly and is submitting the form when the 'Generate' button is pressed.
I would be extremely grateful for any advice on this
This is how I have it set at present:
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
<script type="text/javascript" language="Javascript">
function RequiredTextValidate() {
//check all required fields are completed
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
document.getElementById("<%=CompletedByTextBox.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
document.getElementById("<%=CompletedExtTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
document.getElementById("<%=EmployeeNoTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
document.getElementById("<%=EmployeeNameTextBox.ClientID %>").focus();
return false;
}
return true;
}
function CheckDateTime() {
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (document.getElementById("<%=SickDateTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickDateTextBox.ClientID %>").value.match(re)) {
alert("Invalid date format: " + document.getElementById("<%=SickDateTextBox.ClientID %>").value);
document.getElementById("<%=SickDateTextBox.ClientID %>").focus();
return false;
}
// regular expression to match required time format
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re)) {
alert("Invalid time format: " + document.getElementById("<%=SickTimeTextBox.ClientID %>").value);
document.getElementById("<%=SickTimeTextBox.ClientID %>").focus();
return false;
}
return true;
}
function ReasonAbsenceValidate() {
//check that reason for absence field is completed
if (document.getElementById("<%=ReasonTextBox.ClientID%>").value == "") {
alert("Reason for absence field cannot be blank");
document.getElementById("<%=ReasonTextBox.ClientID%>").focus();
return false;
}
return true;
}
function ReturnDateChanged() {
// check that either Return date or Date Unknown fields are completed
var ReturnDateValid = document.getElementById("<%=ReturnDateTextBox.ClientID%>").value;
var ReturnDateUnknown = document.getElementById("<%=ReturnUnknownCheckBox.ClientID%>").checked;
if (ReturnDateUnknown.checked)
{
ReturnDateValid.disabled = false;
ReturnDateUnknown.disabled = "disabled";
}
if (ReturnDateValid == "" && ReturnDateUnknown == "") {
alert("You must enter at least one field for anticipated return");
return false;
}
return true;
}
function FirstDateChanged() {
// check that either First date of sickness or Date Unknown fields are completed
var FirstDateValid = document.getElementById("<%=FirstDateTextBox.ClientID%>").value;
var FirstDateUnknown = document.getElementById("<%=FirstDateUnknownCheckBox.ClientID%>").checked;
if (FirstDateUnknown.checked)
{
FirstDateValid.disabled = false;
FirstDateUnknown.disabled = "disabled";
}
if (FirstDateValid == "" && FirstDateUnknown == "") {
alert("You must enter at least one field for first day of sickness");
return false;
}
return true;
}
function ActualDateChanged() {
// check that either Actual date of return or Date Unknown fields are completed
var ActualDateValid = document.getElementById("<%=ActualDateTextBox.ClientID%>").value;
var ActualDateUnknown = document.getElementById("<%=ActualDateUnknownCheckBox.ClientID%>").checked;
if (ActualDateUnknown.checked)
{
ActualDateValid.disabled = false;
ActualDateUnknown.disabled = "disabled";
}
if (ActualDateValid == "" && ActualDateUnknown == "") {
alert("You must enter at least one field for actual date of return");
return false;
}
return true;
}
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
</script>
update function like following:
You need to return flase in case of invalid input to prevent form from being posted.
function ValidateFields() {
//Validate all Required Fields
if (RequiredTextValidate() && CheckDateTime() && ReasonAbsenceValidate() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged()) {
return true;
} else {
return false;
}
}
Update
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
condition seems to be wrong. It should be like following.
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value == '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
Use == instead of != operator.

JQ and Js how to Validate content null (Spacebar)

My JS Here:
$('input[type=submit]').click(function () {
var val = $('#message_content').sceditor('instance').val();
if( val == "" || !val ) {
alert('Content Cannot Null');
return false;
}
return true;
});
I have one question:
How to validate? If all content is " "(Spacebar) or "   "(full code Spacebar)...Judgment the content is null?
$('input[type=submit]').click(function () {
var val = $.trim($('#message_content').sceditor('instance').val());
if(!val) {
alert('Content Cannot Null');
return false;
}
return true;
});
You can try this.
Trim the whitespace from the input and then check it against ""

Could someone explain why my functions are not working?

So I'm very new to JavaScript and I'm trying a very simple enter text and check it. It doesn't seem to work the way I want it to. I want all of the inputs to go through the checkInputs. After All of them are 100% I want it to check if hoursWorked and horlyRate are numbers above 0. It seems to just move on to the checkNumberValidation without checking if all inputs are filled.
I got:
function checkNumbersValidation(field){
if( isNaN(field) ) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
var test = false;
do{
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
}else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}else {
tests = true;
}
}while (test = false)
}
function handelCalcButtonClicked (e) {
var passFirstTests = false;
var textFields = ["fullName", "hoursWorked", "hourlyRate"];
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
checkInputs(field);
}
if( **something** ) {
var numberFields = ["hoursWorked", "hourlyRate"]
for ( var i = 0; i < numberFields.length; i++ ) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
clearly I don't know what I'm doing. In the function handelCalcButtonClicked I'm not sure how to move on the the next part (the part Saying something). Any help would be nice!
Inside checkNumbersValidation you need to do the isNan call on field.value, not field:
if( isNaN(field.value) )
If you want to know if all of your fields have gone through checkInputs and have passed, you will need checkInputs to return whether or not each field has passed:
function checkInputs(field) {
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
return false;
} else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return false;
}
return true;
}
This will allow you to know if all fields have passed the check:
var passedAllChecks = true;
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
passedAllChecks = checkInputs(field) && passedAllChecks;
}
if(passedAllChecks) {
/* do number validation stuff */
}
What about this:
function checkNumbersValidation(field) {
if (isNaN(field)) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
return;
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
var textFields = ["fullName", "hoursWorked", "hourlyRate"],
numberFields = [ "hoursWorked", "hourlyRate"],
i,
field;
for (i = 0; i < textFields.length; i++) {
field = document.getElementById(textFields[i]);
checkInputs(field);
}
for (i = 0; i < numberFields.length; i++) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
or:
function checkInput(field, isnumber) {
if (!field) return;
if (isnumber === true && isNaN(field)) {
field.value = "Must be a number";
field.focus("");
return;
}
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return;
}
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
checkInput(document.getElementById('fullName');
checkInput(document.getElementById('hoursWorked', true);
checkInput(document.getElementById('hourlyRate', true);
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});

Javascript Focus Is Not Working on Aspx Page

Hy Guys,
Please Look at the code and Try to Help Out. The function ive written is not working but its RUNNING properly. Its about To set focus on next content on page im using it on an ASPX page. Heres my code Below :
function SetFocusOnSave(CTag,NTag)
{
alert('Running'+CTag+NTag);
var CurrentTag=document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ( (event.keyCode==13)||(event.keyCode==9) )
{
if(CurrentTag.value=="")
{
alert("Please Enter Detail First");
CurrentTag.focus();
}
if(CurrentTag.value!="")
{
event.returnValue=true;
document.getElementById(NextTag).focus();
}
}
}
snametxt.Attributes.Add("onkeypress",
SetFocusOnSave('<%=snametxt.ClientID%>','<%=sdesctxt.ClientID%>');");
have you tried to replace
document.getElementById(NextTag).focus();
with
NextTag.focus();
?
You have to add return false; after you found the false in validation otherwise the flow will continue till end.
Try this function:
function SetFocusOnSave(CTag, NTag) {
alert('Running' + CTag + NTag);
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ((event.keyCode == 13) || (event.keyCode == 9))
{
if (CurrentTag.value == "")
{
alert("Please Enter Detail First");
CurrentTag.focus();
return false;
}
if (CurrentTag.value != "") {
event.returnValue = true;
NextTag.focus();
return false;
}
}
};
Hy Guys Ive Tried A NEW CODE AND Fortunately Its Working Fine Here its my Code
function Navigation(CTag, NTag, Number) {
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
var IsNumber = Number; //Checking if value is number
if (NextTag.disabled == true) {
NextTag.disabled = false;
NextTag.className = "txt";
}
if (event.keyCode == 9) {
CurrentTag.focus();
event.returnvalue = false;
}
if (event.keyCode != 9) {
if (event.keyCode == 13) {
if (IsNumber == "Y") {
if (NextTag.disabled == true) {
NextTag.disabled = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (isNaN(CurrentTag.value)) {
alert("Please Enter A Valid Number");
CurrentTag.value = "";
CurrentTag.focus();
}
}
if (IsNumber == "N") {
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
}
}
}
};
Thanks ya'll !! :)

Categories

Resources