jQuery not returning any value - javascript

I have some code that checks if the contents of the form is valid. checkEmpty, checkNumeric and checkEmail is working fine if i comment out the checkFile function. But if I include checkFile, it breaks the code causing the function not to return any value.
Here is the checkFile function. It's supposed to check the file extension.
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
Also the function should be working fine. I tried it seperately to see if it gets the extension properly.
Here is the whole code in case its needed
$(window).load(function() {
// validations
$.fn.checkEmpty = function(emp) {
if(emp === ""){
alert("field is empty");
return false;
}else{
alert("not empty");
return true;
}
};
$.fn.checkEmail = function(email) {
var regex = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if(regex.test(email)){
alert("mail is valid");
return true;
} else {
alert("mail is invalid");
return false;
}
};
$.fn.checkNumeric = function(value) {
// 10 digits for phone number ?
/*
if (value.length !== 10 || value === "" || !$.isNumeric(value)) {
alert("not a numerical value");
} else {
alert("numerical value");
}*/
var regex =new RegExp(/^(?:\d*\,\d*|\d+)$/);
if(regex.test(value) && value!==""){
alert("numerical value");
return true;
} else {
alert("not numerical value");
return false;
}
};
$.fn.checkFile = function(fileValue) {
//var fileName = contactform.cv.value;
var extension = fileValue.substring(fileValue.lastIndexOf('.') + 1);
alert(extension);
if(extension === 'jpg' || extension === 'jpeg' ||extension === 'docx' ||extension === 'pdf' ||extension === 'xlsx'){
alert("correct extension");
return true;
}else{
alert("incorrect extension");
return false;
}
};
$.fn.checkField = function() {
var empty = "empty";
var numeric = "numeric";
var email = "email";
var file = "file";
var flag=0;
var retval;
$("input:text").each(function() {
var required = $(this).data("reqs");
if(required.toLowerCase().indexOf(empty) !== -1){
retval = $(this).checkEmpty($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if (required.toLowerCase().indexOf(numeric) !== -1){
retval = $(this).checkNumeric($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
if(required.toLowerCase().indexOf(email) !== -1){
retval = $(this).checkEmail($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
$("input:file").each(function() {
if(required.toLowerCase().indexOf(file) !== -1){
retval = $(this).checkFile($(this).val());
if(retval === false){
flag++;
$(this).after('<span style="color:red">*</span>');
}
}
});
alert(flag);
return (flag > 0) ? false : true;
};
});
Thanks for any help.

As Bergi pointed it out, it doesn't make much sense to add the function to the prototype if you pass it the filename as a parameter...
However, adding it to the prototype can be a good idea if you actually use this within the method:
$.fn.checkFile = function(){
var filename = $(this).val();
if (/(?:jpe?g|docx|pdf|xlsx)$/.test(filename)){
return true;
}else{
return false;
}
};
You can test this method at http://jsfiddle.net/NVvzN/. Try choosing different files from your computer to see how it works.
PS: my guess is, if you accept .docx and .xlsx, you should also accept .doc and .xls; in that case, the regular expression would be /(?:jpe?g|docx?|pdf|xlsx?)$/

Related

Console log for foreach javascript didn't show up

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

validate form and send data to php page using ajax jquery

i am trying to send form data to php page before that i wan to validate all required inputs. bellow is my jquery.
$('form#Wall_Post').submit(function(event) {
event.preventDefault();
type = $('.shareType').val();
for (var i = 0; i < formData.length; i++) {
if (!formData[i].value && formData[i].name == 'message') {
alert('Message could not be empty');
return false;
}
if (type == 'photos') {
var fileName = document.getElementById("image").value
if (fileName == "") {
alert("Browse to upload a valid File with png/jpg/gif extension");
return false;
} else if (fileName.split(".")[1].toUpperCase() == "PNG") {} else if (fileName.split(".")[1].toUpperCase() == "JPG") {} else if (fileName.split(".")[1].toUpperCase() == "JPEG") {} else if (fileName.split(".")[1].toUpperCase() == "GIF") {} else {
alert("File with " + fileName.split(".")[1] + " is invalid. Upload a validfile with png/jpg/gif extensions");
return false;
}
}
if (type == 'videos') {
if (!formData[i].value && formData[i].name == 'videoUrl') {
alert('Video Url could not be empty');
return false;
}
video = validateVideoUrl();
if (video == false) {
alert('Not a valid youtube/vimeo video URL');
return false;
}
}
if (type == 'location') {
if (!formData[i].value && formData[i].name == 'location') {
alert('Place could not be empty');
return false;
}
if ((!formData[i].value && formData[i].name == 'lat') || (!formData[i].value && formData[i].name == 'lng')) {
alert('Not a valid place');
return false;
}
}
}
btn = $('#btn-share');
btn.button('loading');
// Prevent the form from submitting via the browser
//var form = $(this);
$('#loading').show();
$.ajax({
url: "/update.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: $('form#Wall_Post').serialize(),
success: function(mesg) // A function to be called if request succeeds
{
$('#loading').hide();
$('.wallupdate').html(mesg);
//alert(mesg);
}
});
});
its working fine before add the validation code. i don't understand where i am doing wrong. I am new to jquery.

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

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.

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