Console log for foreach javascript didn't show up - javascript

I've been trying to work on some validation in javascript, just a simple one. But, the error can't show up in the console log. If all the inputs are correct, it will show the "Registration success text" but in the other side, it won't show any of the error text. But it somehow still can get the focus function to the wrong input, only the error texts that are not showing up in the console. I am so confused. Can you guys help me? I'd appreciate that.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
if(name.value === ''){
error.push("Name is required.");
name.focus();
return false;
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
name.focus();
return false;
}
if(uname.value === ''){
error.push("Username is required.");
uname.focus();
return false;
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
uname.focus();
return false;
}
if(email.value === ''){
error.push("Email is required.");
email.focus();
return false;
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
return false;
}
if(passw.value === ''){
error.push("Password is required.");
passw.focus();
return false;
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
confpassw.focus();
return false;
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
if(region.value == 0){
error.push("Region is not selected");
region.focus();
return false;
}
if(gender.value == 0){
error.push("Gender is not selected");
gender.focus();
return false;
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
termss.focus();
return false;
}
if(error.length == 0){
alert("Registration Success!");
} else{
for(var i=0; i<error.length; i++){
console.log(error.length[i]);
};
}
}

You are returning too early so it is never reaching your consoles. You are focusing on multiple fields.
if(passw.value != confpassw.value){
error.push("The password didn't match.");
passw.focus();
confpassw.focus();
return false;
}
You are also doing console.log(error.length[i]); instead of console.log(error[i]);.
function validate(name, uname, email, passw, confpassw, region, gender, termss){
let error = [];
let firstFailedField = null;
const setFirstFailedField = (field) => {
if (!firstFailedField) firstFailedField = field;
};
if(name.value === ''){
error.push("Name is required.");
setFirstFailedField(name);
}
if(name.value.length < 4){
error.push("Length of name is less than 4 characters.");
setFirstFailedField(name);
}
if(uname.value === ''){
error.push("Username is required.");
setFirstFailedField(uname);
}
if(uname.value.length < 8 || uname.value.length > 14){
error.push("Length of username must between 8-14 characters.");
setFirstFailedField(uname);
}
if(email.value === ''){
error.push("Email is required.");
setFirstFailedField(email);
}
if((email.value.indexOf('#') == -1 && email.value.indexOf('.') == -1) ||
(!email.value.endsWith('gmail.com') && (!email.value.endsWith('gmail.co.id')))
|| email.value.indexOf('#')+1 === email.value.indexOf('.')){
error.push("Email is not valid.");
setFirstFailedField(email);
}
if(passw.value === ''){
error.push("Password is required.");
setFirstFailedField(passw);
}
if(confpassw.value === ''){
error.push("Confirmation Password is required.");
setFirstFailedField(confpassw);
}
if(passw.value != confpassw.value){
error.push("The password didn't match.");
setFirstFailedField(confpassw);
}
if(region.value == 0){
error.push("Region is not selected");
setFirstFailedField(region);
}
if(gender.value == 0){
error.push("Gender is not selected");
setFirstFailedField(gender);
}
if(!termss.checked){
error.push("Please agree to the terms and conditions if you want to proceed.");
setFirstFailedField(termss);
}
if(error.length == 0){
alert("Registration Success!");
return true;
}
error.forEach((err) => (console.log(err)));
if (firstFailedField && typeof firstFailedField.focus === 'function') firstFailedField.focus();
return false;
}

Related

Unknown error the true part of if state dosen't work

I've write a code for simple pass and username form that will show up a content if u entered the user and password correct
but it seems like there is a logical error on it that I can't find
function show() {
if (document.getElementById("user").value == "ahmed" && document.getElementById("pass").value == "ahmed") {
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass1").style.visibility = "hidden";
} else if (document.getElementById("user").value != "ahmed" && document.getElementById("pass").value != "ahmed") {
alert("Password and username is incorrect")
} else if (document.getElementById("pass").value != "ahmed") {
alert("Password is incorrect");
} else if (document.getElementById("user").value != "ahmed") {
alert("Username is incorrect")
}
}
The function work when I entered a wrong pass or username but when I entered them right nothing oth this code , the page just refresh automatically
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass1").style.visibility = "hidden";
source
I created a fiddle and it is working fine
I don't know why it is not working for you. look at the fiddle
https://jsbin.com/vezito/edit?html,js,output
function show() {
var content = document.getElementById("content");
var name = document.getElementById("name");
var pass = document.getElementById("pass");
if (name.value == "ahmed" && pass.value == "ahmed") {
document.getElementById("content").style.visibility = "visible";
document.getElementById("pass").style.visibility = "hidden";
} else if (name.value != "ahmed" && pass.value != "ahmed") {
alert("Password and username is incorrect");
} else if (pass.value != "ahmed") {
alert("Password is incorrect");
} else if (name.value != "ahmed") {
alert("Username is incorrect");
}
}

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;
}

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.

Jquery form validation coding

My Jquery validation is not working, below is the script coding. I am getting a
Fatal error: Uncaught exception
error and not sure why. I know one of the reasons can be the validation code isnt correct. Is the coding correct or is there errors?
<script type="text/javascript">
$('form#contact').submit(function(e) {
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(jQuery('#form_zip').val());
var isValidYear = /^\d{4}$/.test(jQuery('#gradDate').val());
var year_number = parseInt(jQuery('#gradDate').val());
var isValidEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(jQuery('#form_email').val());
var first_name = jQuery.trim(jQuery('#first_name').val());
var last_name = jQuery.trim(jQuery('#last_name').val());
var form_email = jQuery.trim(jQuery('#form_email').val());
var street = jQuery.trim(jQuery('#street').val());
var city = jQuery.trim(jQuery('#city').val());
var state = jQuery.trim(jQuery('#state').val());
var isValidPhone = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/.test(jQuery('#phone_day').val());
function validZip(zip)
{
if (zip.match(/^[0-9]{5}$/)) {
return true;
}
zip=zip.toUpperCase();
if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
return true;
}
if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
return true;
}
return false;
}
if(!validZip(jQuery('#form_zip').val())){
alert('Please enter a valid Zip Code.');
}
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){
alert('Please enter a valid High School Graduation Year.');
}
else if(!isValidEmail (jQuery('#form_email').val())){
alert('Please enter a valid Email Address.');
}
else if(first_name.length <= 0 || first_name == 'First Name' || (!first_name.match(/[a-zA-Z]/)) || (first_name.match(/[0-9]/))){
alert('Please enter your First Name.');
}
else if(last_name.length <= 0 || last_name == 'Last Name' || (!last_name.match(/[a-zA-Z]/)) || (last_name.match(/[0-9]/))){
alert('Please enter your Last Name.');
}
else if(street.length <= 0 || street == 'Street Address'){
alert('Please enter your Street Address.');
}
else if(city.length <= 0 || city == 'City'){
alert('Please enter your City.');
}
else if(state.length <= 0 || state == 'State'){
alert('Please enter your State by 2 letter abbreviation.');
}
else if(country.length <= 0 || country == 'Other'){
alert('Please enter your Country.');
}
else if(!isValidPhone){
alert('If your phone number is correct, close this box and then Click the button in the form.');
}
else {
$('form#mainform').submit();
}
return false;
}
return false;
}
});
</script>
You have php inside your JavaScript code:
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){

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

Categories

Resources