How to validate multi-functions using Javascript in .asp - javascript

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.

Related

Javascript Validation not working (onSubmit)

Vaidation function called on submit.
HTML
<input type="submit" class="submit" value="submit">
JS
window.load = function() {
var form = document.getElementById('form');
form.onsubmit = function(e) {
return validate(); // will be false if the form is invalid
}
}
Validate()
function validate() {
var x = document.forms["form"]["fname"].value;
var y = document.forms["form"]["pname"].value;
var email = document.forms["form"]["email"].value;
var phone = document.forms["form"]["phone"].value;
var date = document.forms["form"]["date"].value;
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
return false;
alert('wass');
if (x==null || x == "" || isNaN(x) == false) {
alert("Check Name, It can't have numbers. You can use Roman numbers.");
return false;}
else if (y == null || y == "") {
alert("Picture Name must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid Date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid Month ");
return false;
}else if(year =='' || year<1800 || year >2016){
alert("Enter valid Year ");
return false;
}
//Function used to make colors red instead of individual codelines
function makeRed(inputDiv){
inputDiv.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.color="#FFFFFF";
}
//Function made to clean the divs when the validation is met.
function makeClean(inputDiv){
inputDiv.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.color="#000000";
}
}
Form still gets submitted. Possible issues?
You'll need to prevent the default form submission using:
e.preventDefault();
Place this above your validate function.
Then use the submit() function on the form to actually submit the form provided your validation passes.
At the minute your form is submitting regardless.
You need to prevent default functionality of form submit, by calling e.preventDefault(). In your case:
window.load = function () {
document.getElementById('form').onsubmit = function (e) {
if (!validate()) {
e.preventDefault();
}
}
}

javascript validating in the wrong order

function validateForm() {
var name = document.forms["myForm"]["name"].value;
if (name == undefined || name == null || name == "") {
alert("Name must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (name.match(letters)) {
return true;
} else {
alert('Name must have alphabet characters only');
document.forms["myForm"]["name"].focus();
return false;
}
}
function validateForm() {
var unit = document.forms["myForm"]["unit"].value;
if (unit == undefined || unit == null || unit == "") {
alert("Unit must be filled out");
return false;
}
var alpha = /^[0-9a-zA-Z]+$/;
if (unit.match(alpha)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
document.forms["myForm"]["unit"].focus();
return false;
}
}
The validation works but it starts from the unit field instead of the name, when I fill out the unit field with the right characters and submit it doesn't go back to validate the Name field, please need serious advice?
You cannot have 2 functions with the same name as the second one will override the first. Merge the functions like so:
function validateForm() {
var formIsValid = true;
var name = document.forms["myForm"]["name"].value;
if (name == undefined || name == null || name == "") {
alert("Name must be filled out");
formIsValid = false;
} else if (!name.match(/^[A-Za-z]+$/)) {
alert('Name must have alphabet characters only');
document.forms["myForm"]["name"].focus();
formIsValid = false;
}
var unit = document.forms["myForm"]["unit"].value;
if (unit == undefined || unit == null || unit == "") {
alert("Unit must be filled out");
formIsValid = false;
} else if (!unit.match(/^[0-9a-zA-Z]+$/)) {
alert('User address must have alphanumeric characters only');
document.forms["myForm"]["unit"].focus();
formIsValid = false;
}
return formIsValid;
}

Javascript Form Validation check

I am doing some homework about form validation and have write some code but it is not valid with some problems. Can someone tell me what's wrong in them and fix them? Thanks
function formCheck() {
var form = document.forms["contact_form"];
if(form["first_name"]["last_name"].value == "") {
alert("Please fill in the required name.");
form["first_name"]["last_name"].focus();
return false;
}
var zip = /^\d{5}(-\d{4})?$/.test;
if(zip.test(form["zip_code"]).value == false){
alert("Please fill in a valid zipcode.");
form["zip_code"].focus();
return false;
}
var phone = /^\[0-9]{10}$|^\([0-9]{3}\)[ ]?[0-9]{3}-[0-9]{4}$/
if(phone.test(form["phone_number"]).value == false){
alert("Phone number input format is not valid.");
form["phone_number"].focus();
return false;
}
var email = /^([a-zA-Z0-9_.])+#[a-zA-Z0-9]([a-zA-Z0-9])+\.([a-z])+$/
if(email.test(form["email_address"].value == false){
alert("Email format is not valid.");
return false;
}
form.submit();
return true;
}
This seems incorrect:
if(form["first_name"]["last_name"].value == "") {
alert("Please fill in the required name.");
form["first_name"]["last_name"].focus();
return false;
}
You may want to replace that with:
if(form["first_name"].value == "") {
alert("Please fill in the required first name.");
form["first_name"].focus();
return false;
}
if(form["last_name"].value == "") {
alert("Please fill in the required last name.");
form["last_name"].focus();
return false;
}

Conditional valdiation of required fields

I have a page where the user enters their address. I want to make city, state and zip code required fields, but here's the catch. Either the user is required to enter both the city and the state OR they are required to enter the zip code. How do I do this javascript?
For now I have
function Form(f) {
for (var n = 0; n < f.elements.length; n++) {
if ((f.elements[n].name).indexOf("zip_code") > -1) {
var zipcode = f.elements[n].value;
if (zipcode.length == "") {
if ((f.elements[n].name).indexOf("cityname") > -1) {
var city = f.elements[n].value;
if (city.length == "") {
alert("Enter City name");
break;
}
}
if ((f.elements[n].name).indexOf("statename") > -1) {
var state = f.elements[n].value;
if (state.length == "") {
alert("Enter State name");
break;
}
}
} else {
//return true; then do something
return false;
}
} else if (zipcode.length == "") {
alert("Enter zipcode");
break;
return false;
}
}
}
Can you please try this?
function Form(f) {
var cityname = document.getElementsByName('cityname')[0].value;
var statename = document.getElementsByName('statename')[0].value;
var zip_code = document.getElementsByName('zip_code')[0].value;
if( (cityname.length==0 && statename.length==0 ) ){
if(zip_code.length==0){
alert("Enter zipcode");
return false;
}
return true;
}else if( (cityname.length==0 || statename.length==0 ) ){
if (cityname.length == 0) {
alert("Enter City name");
return false;
}else if (statename.length == 0) {
alert("Enter State name");
return false;
}
return true;
}
}
Something like this should help
if( zipcode.length){
/* validate zipcode*/
}else{
if( city.length && state.length){
}else{
/* must have city and state*/
}
}
use a variable flag.
flag = 0;
if city and state
make flag as 1
if zip
make flag as 1
if flag==0 then validation failed
else allow to submit form

nested if else in javascript

I have trouble with the nested if structure in javascript. Any help is appreciated.
function validateForm()
{
var a = document.forms["demo1"]["addr1"].value;
var b = document.forms["demo1"]["city"].value;
//var c = document.forms["demo1"]["fname"].value;
//var d = document.forms["demo1"]["lname"].value;
//var f = document.forms["demo1"]["phno"].value;
//var g = document.forms["demo1"]["email"].value;
//var g1 = document.forms["demo1"]["cemail"].value;
//var h = document.forms["demo1"]["pwd"].value;
//var h1 = document.forms["demo1"]["cpwd"].value;
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
break;
}
else if(a=="" || a==null)
{
alert("Please enter your address");
return false;
break;
}
else {return true;}
}
<form name = "demo1" action = "exp2.php" onsubmit = "return validateForm()" method = "POST">
The code works fine(as intended) if there is only one if statement. But I am not getting the intended result if more than one if else is been deployed.
Regards,
Mani
First, you don't need break statements, they're useless in this context.
Second, you don't need to nest and, in fact, you shouldn't since checking of a and b is independent of each other:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
return true;
What about shorten ur code with reusable isEmpty function
function validateForm()
{
var isEmpty = function ( name , label ){
var val = document.forms["demo1"][ name ].value;
if( ! val )
{
alert("Please enter your "+ label );
return true;
}
return false;
}
return !isEmpty( 'city', 'city') &&
!isEmpty( 'addr1', 'address');
}
isEmpty return true or false
if(b=="" || b==null) {
alert("Please enter your city");
return false;
}
else if(a=="" || a==null) {
alert("Please enter your address");
return false;
}
else {
return true;
}
Like paxdiablo says you can use two separate if statements.
But if you only want to require an address when a city is entered you must realize that this is not a nested if statement. This is:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
else
{
if(a=="" || a==null)
{
alert("Please enter your address");
return false;
}
else
{
return true;
}
}
A more reabable version would be, imo:
if(b=="" || b==null)
{
alert("Please enter your city");
return false;
}
if((b=="" || b == null) && (a=="" || a==null))
{
alert("Please enter your address");
return false;
}

Categories

Resources