Validating drop down menu JavaScript - javascript

I'm working on an existing site with a contact form that's using JavaScript to validate the fields. The original developer wrote the JavaScript and it isn't validating one of the fields correctly. the Field is a dropdown list and it has a default value that they don't want to be selectable, so I need it to return an invalid response if the default option is selected to force the user to make a selection.
Any help would be greatly appreciated.
// Check to make sure Area of Interest is Valid
var areaVal = $("#req_area").val();
var areaRegexObj = /^\s*[\w\s]*\s*$/;
if (areaRegexObj.test(areaVal)) {
isValid = (isValid == false) ? false : true;
} else {
$("#req_area").val("Please specify your Area of Interest");
isValid = false;
}

Try
var areaVal = $("#req_area option:selected").val();
if (!areaRegexObj.test(areaVal))
$("#req_area").val("Please specify your Area of Interest");
It is a good idea to have server side validation (if not already) so that a user won't disable JS and submit the form anyway.

Related

Trying to add hCaptcha to my site but don't understand this javascript code

Javascript isn't really my strong point. I already have the php working for the captcha on the backend but i want to be able to validate the form with JS to prevent the user from sending a form when the captcha hasn't been completed.
This is the example the hcaptca site gives:
https://medium.com/#hCaptcha/using-hcaptcha-with-php-fc31884aa9ea
And here is the JS code they give as an example.
$("form").submit(function(event) {
var hcaptchaVal = $('[name=h-captcha-response]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I'm not 100% sure but that appears to be Jquery and my site does not use Jquery. so i need a vanilla JS solution.
Let me try to explain:
$("form").submit(function(event) { }
// When the form is submitted
var hcaptchaVal = $('[name=h-captcha-response]').value;
// Retrieve the value of the captcha (= the value of an HTML element with the tag name="h-captcha-response"
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the Captcha");
}
// If the value of the captcha is empty, stop the form submission and alert the user
So if you are searching for a Vanilla JS solution, it's not that hard, all you have to do is convert the jQuery parts :
document.querySelector("#yourFormId").addEventListener("submit", function(event) {
var hcaptchaVal = document.querySelector('[name="h-captcha-response"]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});

How do I display an error on a field for a custom form validator?

I have already built a form validator in JS, a portion of which is displayed below. I just need help in displaying an error and scrolling to the field.
Okay, so each <input> will have attributes specifying the validation they need, eg:
<input data-mandatory="yes" data-validation="phone" data-max-digits="10">
There attributes are parsed at the time of form submission, and if I come across an errornous field I need to scroll to that field and display an error in English (multilingual not needed).
var $form = $('#main-form');
$form.submit(function(event) {
event.preventDefault();
// per field
$form.find("input,textarea").each(function(f, field){
// read metadata
var type = $(field).attr("type");
var mandatory = $(field).data("mandatory");
var maxDigits = $(field).data("max-digits")) || 1000;
var validation = $(field).data("validation");
// read value
var value = $(field).value();
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
// HOW DO I SHOW AN ERROR AT THE CURRENT FIELD?
// and how do I scroll to it?
}
}
});
});
Edit: I've got a non-trivial amount of code in node.js (5K LOC) which I'm porting to the client side, which is required by my organization. That code is not displayed above.
Edit: I've looked online for an hour but the jQuery form validator libraries that I've seen do not function the way I need. I already have form sanitation & validation code (which supports various data types like phone number, ZIP code, etc) in Node.js which I'm just porting to the client side.
First of all i would recommend to use some free validation plugin. But, if you want for some reason to write it your self, than the answer to your question is:
First you need to have the error message hidden somewhere in your markup. There is a number of ways to do this. Most common solution would be something like that:
<div>
<input type="text" required />
<p class="error">Error</p>
</div>
Than you need to display it, in your example it could be done like this:
// process mandatory textfields
if (type == "text" || type == "number"){
var strValue = trim(value.toString());
if (mandatory && strValue.length == 0){
//show error
$(this).parent().find('.error').show();
//scroll
$('html, body').animate({
scrollTop: $(this).offset().top
}, 2000);
return; // stop validation(becouse you dont want to scroll more times)
}
}
You will need to figure out some more things (like hide all the errors before validating again), but this should answer your question.

Targeting document.getElementById to sub templates?

I cannot get certain fields in a form to unlock. I have a javascript file that works on certain pages, but not on others.
I am using document.getElementById to target form fields to disable or enable them depending on certain inputs. It works fine on one page but not another. I have double checked all my ids and they are correct. Here is the javascript:
var pass2 = document.getElementById("password").value;
if (pass1 == pass2) {
//start profile
document.getElementById("premium-text").innerHTML = "Congratulations! You have unlocked the premium fields!";
document.getElementById("premium").style.background = "#d1fdd3";
document.getElementById("premium").style.borderColor = "#019408";
document.getElementById("description").disabled = false;
document.getElementById("fax-number").disabled = false;
document.getElementById("facebook-url").disabled = false;
document.getElementById("twitter-url").disabled = false;
document.getElementById("google-plus-url").disabled = false;
document.getElementById("linkedin-url").disabled = false;
document.getElementById("type").disabled = false;
document.getElementById("city").disabled = false;
document.getElementById("status").disabled = false;
document.getElementById("price").disabled = false;
document.getElementById("bedrooms").disabled = false;
document.getElementById("bathrooms").disabled = false;
document.getElementById("size").disabled = false;
document.getElementById("property-id").disabled = false;
document.getElementById("video-url").disabled = false;
document.getElementById("featured").disabled = false;
The only difference in the pages is one has the form fields in the template (form ids are directly in edit-profile.php) and the other page pulls in the form fields from a sub template that has the ids in it (submit-property.php pulls form fields from a sub template partials/templates/submit-form.php).
What do I need to do to target the fields that are pulled in from the sub-template? The id gets pulled into the page source code so I assumed the document.getElementById would work fine, but it is not for some reason.
On this page the javascript is working but not on this page. You have to create an account to have access to these pages. The user is test1 and pass is testpass.
The password to unlock the form fields is QuL7eD
Make sure you don't have same multiple ids. If you can post your code I'll be able to assist you better.
I split the Javascript into two seperate files and that seemed to work. I can only assume this had something to do with the fact that there were different field ids on each page and when the document.getElementById ran and didn't find all the ids (since some were on a different page) that is why it wasn't working.

Custom validation script on submit for PDF - Can't get it working

I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}

Modifying form values onSubmit but hide from user

Im attempting to modify a JAvascript login form. The form action calls a DLL so I cant modify it to include the modifications I want to make.
Here is the javascript function Im using:
function SubmitForm() {
var Domain = "#domain.com"
var txtBox = document.getElementById('username');
if(txtBox.value.indexOf("\\") != -1){
return;
}
if((txtBox.value.indexOf("#") == -1) && (txtBox.value != "")) {
txtBox.value += Domain;
return;
}
}
Basically checks the username for \ and # chars first, if it doesnt contain those values it adds the Domain to the username.
Ive added this to the <form> onsubmit="return(SubmitForm());" to calls and use this function. However I dont want the user to see the domain been added to the username.
Is there any other way to do this>
Don't modify the input box, then. Rather have the onSubmit handler write whatever you want into a type="hidden" field which is used instead.
If you absolutely can't change this on the server side, you could always change the ID of your username input field, and create a hidden field with an ID of username that you can populate with the user's input plus your domain.

Categories