Catptcha validation Issue - javascript

I created a Captcha validator but It overrides the Dreamweaver Spry validator that validates the entire form and submits it. How do I get it to get it to append to or work with the spry validator. The captcha validator is below. I don't want it to submit the form. I want it to proceed to the spry validator that validates the entire form.
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}

1.I solved the problem by removing the checkform function above
2. Then create an input field and validate it against the output of the txtCaptcha generated by the code below. That way my Form gets validated by my original validator. (no Conflicts
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
var spryconfirm1 = new Spry.Widget.ValidationConfirm("spryconfirm1", "txtCaptcha");
</script>

Related

HTML Form validation in raw javascript with DOM

It seems i have broken my working code. The form now submit without file validation, which it should not.
document.addEventListener('DOMContentLoaded', function(){
function validate(){
var pTagMsg = document.querySelector('#ptagmsg');
var inpsText = document.querySelectorAll('.textinputs');
var inpFile = document.querySelector('#upload');
var regForm = document.querySelector('.regform');
for(let i = 0; i < inpsText.length; i++){
// check if text input fields are not filled.
let fieldValue = inpsText[i].value.length;
if(fieldValue == 0){
inpsText[i].focus();
inpsText[i].style.backgroundColor = 'red';
return false;
} else if (fieldValue != 0){
// if input fields containn values.
inpsText[i].style.backgroundColor = 'green';
}
}
var fileObjList = inpFile.files;
var fileObj = inpFile.files[0];
var fileValue = inpFile.value;
var fileName = fileObj.name;
var fileExt = fileObj.name.slice(-4);
var fileSize = Math.round(fileObj.size / 1024);
var size = 300; // size in kb.
if(fileObjList.length === 0){
pTagMsg.textContent = "Attachment Required";
pTagMsg.style.backgroundColor = 'red';
return false;
} else {
// check for extension and size.
if((fileExt == '.pdf') && (fileSize <= size)){
pTagMsg.textContent = 'file selected, OK!: ' + fileExt +', '+ fileSize;
pTagMsg.style.backgroundColor = 'green';
} else {
pTagMsg.textContent = 'file must be: '+ fileExt + 'and size of: ' + size + 'kB !';
}
}
}
// calling the submit event on the form.
regForm.addEventListener('submit', validate);
});
Firstname:
Email:
Surname:
Lastname:
ward:
location landmark:
date:
describe
First of all, I hope you can share your code in beautiful format and indentation.
When you submit form and want to do a validation, you should prevent it from its' default action. Then after all checking complete, you could continue submitting the form.
function validate(e){
e.preventDefault();
// rest of your code ...
if(everythingInvalid) {
alert("Your form invalided");
return;
}
regForm.submit();
}
regForm.addEventListener('submit', validate)
Please see others references:
Google: "validate form before submit"
Google: "submit form after preventDefault"
https://laracasts.com/discuss/channels/laravel/how-to-continue-to-submit-a-form-after-preventing-it-with-jquery
https://www.w3schools.com/js/js_validation.asp

Why is my Javascript form validation not working properly?

Why is my validation failing on second attempt here? On first attempt the validation works fine, but on the second run, it will accept inappropriate values in the email field. The first two fields work fine, but the third field will accept any text after the first run. However it only validates if I change the value in the email field, otherwise it will keep displaying the error and failing to validate like it should.
function validate(){
clearErrors();
var errorFlag = true;
var name = document.getElementById("name");
nameVal = name.value;
if(nameVal.length === 0){
var nameError = document.getElementById("nameError");
nameError.style.display = "block";
errorFlag = false;
}
var phone = document.getElementById("phone")
var phoneVal = phone.value;
if(isNaN(phoneVal) || (phoneVal < 1000000000 || phoneVal >10000000000)){
errorFlag = false;
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "block";
}
var email = document.getElementById("email");
var emailVal = email.value;
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
errorFlag = false;
var emailError = document.getElementById("emailError");
emailError.style.display = "block";
}
return errorFlag;
}
function clearErrors(){
var nameError = document.getElementById("nameError");
nameError.style.display = "none";
var phoneError = document.getElementById("phoneError");
phoneError.style.display = "none";
var emailError = document.getElementById("emailError");
emailError.style.display = "none";
}
Your validator will fail on the email, because you are feeding a string to .match, when it needs a regex.
You also have to call .match on the email itself, with the regex as the argument.
You also need to negate the return value to check if it does not match, or use .test.
This bit:
var reStr = "^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$";
if((reStr.match(emailVal))){
Should be replaced with:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!emailVal.match(re)){
Of if you can't use a regex literal for some reason:
var re = new RegExp("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$", "i");
if(!emailVal.match(re)){
Or using .test instead of .match:
var re = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
if(!re.test(emailVal)){
Note the i for case-insensitive matching, so emails don't have to be entered in all-caps.

How to allow validation for multiple email addresses using javascript

I am using javascript to validate my page, I have done the validation for email which should follow the basic rules of email id. But I need the validation to allow multiple email addresses. Can anyone please help in adding this. Thanks in advance.
Here is JS Code:
function function1(){
var exp = /^(([^<>()[\]\\.,;:\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,}))$/;
var emailid = document.getElementById('mailid').value;
if(emailid == '' || emailid == null){
document.getElementById('error4').innerHTML = "* Enter Email ID";
document.getElementById('mailid').focus();
return false;
}else{
document.getElementById('error4').innerHTML = "";
}
if (!exp.test(emailid)) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
}
You could do something like this:
var emails = emailid.split(",");
emails.forEach(function (email) {
if(!exp.test(email.trim()) {
document.getElementById('error4').innerHTML = "* Invalid Email";
document.getElementById('mailid').focus();
return false;
}
});
You should split your emailid string into an array and then check the emails one by one
var emails = emailid.split(',');
You can know more about the split method here http://www.w3schools.com/jsref/jsref_split.asp
Assuming the addresses are separated by comma you could do something like this:
(untested but you should get the idea)
var theString = "an.address#domain.ext, an.other.address",
stringProper = theString.replace(/\s/g,''),
addresses = stringProper.split(','), //creates an array of every email
allValid = true;
for (var i = addresses.length - 1; i >= 0; i--) {
if (addresses[i] == 'an.other.address') {
isValid = true;
} else {
isValid = false;
}
if(!isValid) {
allValid = false;
break;
}
};
function isEmail (theString) {
var exp = /^(([^<>()[\]\\.,;:\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,}))$/;
return exp.test(theString)
}

Convert multiple alerts to one alert

I'm using javascipt to validate a form and the code is like below,
function validateForm() {
console.log("start check form");
var errors = [];
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var fnElem = document.getElementById("name");
var lnElem = document.getElementById("phone");
var firstName = fnElem.value;
var lastName = lnElem.value;
// etc...
// validate required fields
if (firstName === "") {
errors.push({
elem: firstName,
message: "name can't be blank"
});
}
if (lastName === "") {
errors.push({
elem: lastName,
message: "phone can't be blank"
});
}
for(var i=0; i<errors.length;i++){
alert(errors[i].message);
}
return false;
}
and in the for loop it will alert lots of times in the windows.
how can I combine all the alert into one single message..and only alert once.
I know that I can define a string and append one by one, But that seems so fool.
Is there a better way to do this.
First you map the error array to the contained messages: array.map().
Then you can join the messages: array.join().
if (errors.length) {
alert("Errors:\n" + errors.map(function (e) { return e.message; }).join('\n'));
}
Change your loop to append the message to a variable, then alert after the loop:
var messages = "";
for(var i=0; i<errors.length;i++){
messages += errors[i].message + "\n";
}
alert(messages)
for( var sAlert = '', i = 0, iL = errors.length; i < iL; ++i ) {
sAlert += errors[i].message + '\n';
}
alert(sAlert );
I didn't had a closer look at your code but if everything is fine this should solve it :)

how to compare the value

This my code
I am getting email address from database through ajax and mysql it is giving me value in . so in below FUNCTION comparing() i am retriving data from span to compare with the textfield data. but it is not comparing properly.
Please help me out
function validate(pageForm)
{
/************Getting error values in return values***********************/
var returncomparing = "";
/*********************************/
//FIELD WHICH YOU HAVE TO VALDATE
returncomparing += comparing(pageForm.email);
/********************************************/
if (returncomparing != "")
{
document.getElementById('error').innerHTML = returnIndustry;
}
return false;
}
After giving correct EMAIL still it is giving Error ... (Please Provide Login User ID)
function comparing(pageForm){
var error = "";
// var fetchedEmail=document.forms["pageForm"]["email_fetch"].value;
var em=document.forms["pageForm"]["email"].value;
//var emai = document.getElementById('emlTst').value;
var email = document.getElementById('txtHint').innerHTML;
//document.getElementById('emlTst').value = email;
if(em != email){
document.getElementById('error_email2').innerHTML="Please Provide Login User ID";
pageForm.style.borderColor = 'red';
error='5';
}
else if(em == email){
document.getElementById('error_email2').innerHTML="";
error = "";
}
else {
document.getElementById('error_email2').innerHTML="";
pageForm.style.borderColor = '#c7c7c7';
}
return error;
}
/*************************************************************/
var em = $('#email').val().toLowerCase();
var email = $('#txtHint').val().toLowerCase();

Categories

Resources