Form input value validation - javascript

I have a question about contact form. I am not good in javascript. Here we go to the question.
I have a contact form on my website and one of the field called security that is for anti-spammers purpose. Currently, all the fields(except security) will be validated by javascript where i got from somewhere else. And, the field of security, will be validated by php code when submit. The security field is a math question. If you have complete all other fields, but provided a wrong answer to the security field, you will be redirected to the form and be required to do it all over again. I don't want the form to be this way.
Here to test the form --> http://www.jornes.com
What i want is, if the answer to the math question is 50, visitors can only pass the validation and submit the form with a correct answer. I want this value to be validated by javascript.
I'm looking for a solution to make the contact form even better. Any solutions?
Below is the javascript to process my existing form.
function validateForm(){
// set some vars
var name = document.getElementById('name');
var phone = document.getElementById('phone');
var email = document.getElementById('email');
var location = document.getElementById('location');
var findus = document.getElementById('findus');
var inquiry = document.getElementById('inquiry');
var msg = '';
if(name.value.length == ''){
msg+= '*How shall i address you? \n';
name.className = 'inpBoxError';
}
else if(name.value.length < 3){
msg+= '-Your name is too short, my friend! \n';
name.className = 'inpBoxError';
}
else if((name.value.length<3)||(/[^a-z\s\'\-\.]/gi.test(name.value))) { // invalid - must be minimum of 5 character only
msg+= '-Please enter your name with words only! \n';
name.className = 'inpBoxError';
}
else if ((phone.value.length == '')) {
msg+= '*You should have a cell phone, i guess?! \n';
phone.className = 'inpBoxError';
}
else if ((phone.value.length<1)||(/[^0-9]/gi.test(phone.value))) { // invalid - must be minimum of 10 digits only
msg+= '-Only Numeric for Phone Field!(Ex:0123456789) \n';
phone.className = 'inpBoxError';
}
else if ((phone.value.length<10)||(/[^0-9]/gi.test(phone.value))) { // invalid - must be minimum of 10 digits only
msg+= '-Please enter a valid phone number! "10 digits" \n';
phone.className = 'inpBoxError';
}
else if ((email.value.length == '')) {
msg+= '*Email is also a good way for us to communicate. \n';
email.className = 'inpBoxError';
}
else if(!/^([a-z0-9])([\w\.\-\+])+([a-z0-9]?)\#((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(email.value)) { // invalid
msg+= '-Invalid email format! \n';
email.className = 'inpBoxError';
}
else if(location.value.length == ''){
msg+= '*Please tell me where are you from! \n';
location.className = 'inpBoxError';
}
else if(location.value.length < 5){
msg+= '-Location name is too short! I am not sure where is the place. \n';
location.className = 'inpBoxError';
}
else if(purpose.value == ''){
msg+= '*You contact me for...? \n';
purpose.className = 'multipleError';
}
else if(findus.value == ''){
msg+= '*How did you find me? Did i know you? \n';
findus.className = 'inpSelectError';
}
else if(inquiry.value.length == ''){
msg+= '*At least tell me something! \n';
inquiry.className = 'messageBoxError';
}
else if(inquiry.value.length < 50){
msg+= '-Your message is too short! "Minimum 50 characters." \n';
inquiry.className = 'messageBoxError';
}
else if(security.value == ''){
msg+= '*You must provide correct answer to submit this form! \n';
security.className = 'inpBoxError';
}
// SUbmit form part
if(msg == ''){
return true;
}else{
alert(msg);
return false;
}
}

Even the dumbest bot can parse Security: 7+3 perhaps you want to use words or images.
You can use a regex to validate the security form field but even this one could be analysed by spam bots. I would not validate this field in the frontend. The server should test it an in case of an error return the form again with prefilled with the former user input.
If you want you can add a hidden field, that should not filled at all. If your id or label of this hidden field is clever chosen many spam bots will fill something in, and you can use this information to block them.

Related

Validating Phone Number based on country code

How to validate phone numbers based on country codes in Javascript.
For Example: India-starts with 91-xxxxxxxxxx, UK-44-xxxxxxxxxx, SZ-268-22xxxxxx and so on. Like this it should validate other countries country code with phone number which I will enter.
Below is the code which I tried but it is only for one country. Parallelly how to do validate with other countries country code.
function validateMobNo(mobno){
var mobno2;
var flag=false;
var mlen= mobno.length;
//alert(mobno.substr(3,mobno.length-3));
if(mobno.charAt(0)!='+' && mlen==10){
mobno2="+91-"+mobno;
alert("1>>your mobile wants to be in "+mobno2);
flag=true;
}
else if(mobno.charAt(0)=='+'){
if(mobno.substr(0,3)=='+91' && mobno.length==13){
mobno2=mobno.substr(0,3)+"-"+mobno.substr(3,mobno.length-3);
alert("2>>your mobile wants to be in "+mobno2);
flag=true;
}
}
else if(mobno.indexOf("-")<0&&mobno.length==12 && mobno.substr(0,2)=='91'){
mobno2=mobno.substr(0,2)+"-"+mobno.substr(3,mobno.length-2);
alert("3>>your mobile wants to be in "+mobno2);
flag=true;
}
else
alert("Please correct your mobile No");
if(flag==true)
document.mobvalidate.mobno.value=mobno2;
else
document.mobvalidate.mobno.focus()
return flag;
}
Using some method to loop over each country code and evaluates with regular erxpressions:
country_codes=['91-', 'UK-44-', 'SZ-268-22']
phone="91-123456789";
is_valid_number = country_codes.some(elem => phone.match('^' + elem));
console.log(is_valid_number );

How do I loop a request for user input until the user enters information in Acrobat XI

I need to program a form field so the user can't proceed to the next field until the field is filled in. I set it up so a message pops up but the user is still allowed to proceed.
Here's what I've got.
var ConstructionType = this.getField("ConstructionType").value;
if( ConstructionType == "New Residential" )
app.alert("You must enter the Residential Finished Floor Area field before continuing");
else if ( ConstructionType == "Accessory Suite")
app.alert("You must fill in the Residential Finished Floor Area field before continuing");
Here is the code for hiding the fields when I didn't need them.
'if(event.value =="New Commercial") {
this.getField("FixNum").display = display.visible;
this.getField("FinArea").display = display.hidden;
} else if(event.value == "Tenant Improvement"){
this.getField("FixNum").display = display.visible;
this.getField("FinArea").display = display.hidden;
} else if (event.value =="Residential Addition") {
this.getField("FinArea").display = display.hidden;
this.getField("FixNum").display = display.hidden;
}`

Javascript else if statement not working with form validation

I'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value

JavaScript button doesn't work

I am very new to using JavaScript so bear with me. I only finished the different courses found on Codecademy so far.
So I'm trying to make a sign up form for a website where you need a user. I found a pretty cool one on the internet that I changed a bit and also made use of the Datepicker from jQuery. It looks like this:
I got code to check whether the user filled out the different fields but it doesn't seem to work. In my index.html file I included the following file:
<script src="js/signupsubmit.js"></script>
And at the bottom of the form I do this:
<div>
<p id="sign_user" onClick="Submit()">Sign Up</p>
</div>
So good so far. In the JavaScript I have the following code:
function Submit() {
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]{2,5}$/;
var fname = document.form.Name.value,
lname = document.form.LastName.value,
femail = document.form.Email.value,
freemail = document.form.enterEmail.value,
fpassword = document.form.Password.value,
dateObject = $("#datepicker").datepicker(
{
onSelect: function()
{
var dateObject = $(this).datepicker('getDate');
}
});
if( fname == "") {
document.form.name.focus();
document.getElementById("errorBox").innerHTML = "Enter First Name";
return false;
}
if( lname == "" )
{
document.form.LastName.focus() ;
document.getElementById("errorBox").innerHTML = "Enter Last Name";
return false;
}
if (femail == "" )
{
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter your Email Address";
return false;
}else if(!emailRegex.test(femail)){
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter a Valid Email Address";
return false;
}
if (freemail == "" )
{
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter the Email Address";
return false;
}else if(!emailRegex.test(freemail)){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter a Valid Email Address";
return false;
}
if(freemail != femail){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "The Email Addresses don't Match!";
return false;
}
if(fpassword == "")
{
document.form.Password.focus();
document.getElementById("errorBox").innerHTML = "Enter a Password";
return false;
}
if(dateObject == null) {
document.form.datepicker.focus();
document.getElementById("errorBox").innerHTML = "Please Enter a Birthday";
}
}
I am a bit shaky on trying to read the Datepicker too. But otherwise, can you possibly spot what might be missing in this puzzle? When I press the blue "Sign Up" button, literally nothing happens. I can provide more info if needed.
You have a mistake addressing the form: The correct formula is not document.form, but document.forms[0]. Or even better, I recommend you to give the form a specific unique name, and address it by that name:
HTML:
<form name="mydata">...</form>
Javascript:
var fm=document.forms.mydata
Also, take care of lowercase/uppercase lettering: Identifiers in Javascript are case-sensitive, which means that the input "Name" must be always addressed as "Name" (you mispelled that identifier in the line document.form.name.focus()).

Javascript checking # in email

I am trying to check an HTML input form to see if it contains an # symbol.
HTML:
<input id="emailCheck" type="text" name="uid" />
<input type="button" value="Continue" onClick="continuePlease()" />
<br>
<p id="invalidEmail"></p>
Javascript:
var at = document.getElementById("emailCheck").value.indexOf("#");
function continuePlease() {
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}
function changeData() {
document.getElementById("title").innerHTML = "<font color=#33FF00> Information Confirmed </font>";
document.getElementById("lock").innerHTML = "<font color=red>This Account is now locked.</font>";
document.getElementById("time").innerHTML = "<font color=white> You will have 30 minutes to send the provided wallet address the correct amount of Bitcoin or the account will unlock again. </font>";
document.getElementById("daemon").innerHTML = "<font color=white> Our Bit-Daemon is watching the address 24/7, once a payment is made, the contents of the account will be sent to your Email. Thanks, Paypal Trader.</font>";
document.getElementById("pig").innerHTML = "";
document.getElementById("cow").innerHTML = "";
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
}
What's happening is that when it performs the function continuePlease() it does both the code in the IF and in the ELSE.
It should do one or the other, not both.
I think I need a better way to check for the # symbol.
move at assignment as the first line of the continuePlease. I don t think it is doing both it is always doing the else block and check the last line of the else block it is same with if block.
You can use this handy function to test that:
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
You can pass in the email using this:
var email = document.getElementById("email").value;
This function will return either true or false depending on the email string you'll provide.
Do it this way. It should work.
function continuePlease() {
var at = document.getElementById("emailCheck").value.indexOf("#");
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}

Categories