How to prevent certain inputs on certain forms using Jquery? - javascript

I recently had a good setup for preventing gmail, hotmail, yahoo etc. emails from being able to be submitted on our forms for requesting a demo for our company. However, we now have multiple forms on certain pages, some of which we will allow personal emails.
My question is how do I adjust the following script to prohibit the input on a particular form id? Is it possible to simply add something that detects the form ID (let's call it #form-id for now).
// EMAIL DOMAINS TO BLOCK
var emailList = /^([\w-\.]+#(?!gmail.com)(?!yahoo.com)(?!icloud.com)(?!hotmail.com)(?!aol.com)
// ALERT MESSAGE TO BE SHOWN
var emailAlert = 'Please input a valid work email address (NOT Gmail, Outlook, Yahoo, etc.)'
// VALIDATE
$('input[type=submit]').click(function() {
$("input[type=email]").each(function() {
var email = $(this).val().toLowerCase();
if (emailList.test(email)) {
(this).setCustomValidity('');
} else {
(this).setCustomValidity(emailAlert);
}
})
})
// PREVENTS ALERT FROM APPEARING WITH EACH KEYPRESS
$('input[type=email]').on('input', function() {
(this).setCustomValidity('');
});

Without knowing much else about your situation, in basic principle you should be able to scope your code by modifying the selector portion of your jquery function calls.
For example if you wanted to enact this validation only on the form with id #form-id in theory you should be able to change your code to this:
$('#form-id input[type=submit]').click(function() {
$("#form-id input[type=email]").each(function() {
var email = $(this).val().toLowerCase();
if (emailList.test(email)) {
(this).setCustomValidity('');
} else {
(this).setCustomValidity(emailAlert);
}
})
})
// PREVENTS ALERT FROM APPEARING WITH EACH KEYPRESS
$('#form-id input[type=email]').on('input', function() {
(this).setCustomValidity('');
});
The format of this - two sub selectors seperated by a space - means that the 2nd sub-selector will only match when it appears inside the first sub-selector.
Consider example #form-id input[type=submit]
This selector will match on inputs of type submit found inside your form (or any parent element) with id form-id
To do the opposite you could change the selector to:
form:not(#form-id) input[type=submit]

Related

I want to disable the save button if any of the fields have red border

I want to disable the save button until all the fields are valid and not to enable if any one field border turns red. The jsp is included with more jsp's and I am finding it difficult to get the form/div into my java script function
I am triying to get the form/div id dynamically using the jquery but in the JavaScript it fails to the id of the form
onkeyup="checkFieldWithRegExp(jQuery('#SUM-03-inputnumberOfChildren'), jQuery('#teleNumeric'), jQuery('#FO-E012-tableShowMarketingConsent'));
function checkFieldWithRegExp(valueField, regExpField, formIdField) {
var regExp = regExpField.val();
var regNumber = valueField.val();
var formIdValue = $('#formIdField input:not(.hilightBorder)').length();
if (regExp !== null && !new RegExp(regExp).test(regNumber)) {
valueField.addClass('hilightBorder');
valueField.removeClass('hilightGreenBorder')
$('SUM00bSaveButton').disabled=false;
} else if(regExp !== null && new RegExp(regExp).test(regNumber)){
valueField.addClass('hilightGreenBorder');
valueField.removeClass('hilightBorder');
if(formIdValue){
$('SUM00bSaveButton').disabled=false;
}
} else {
valueField.removeClass('hilightBorder');
}
}
I expect to disable the save when page loads and if any of the fields have red border which user input is wrong. Can I please get some help
I believe you are approaching the problem wrong.
From my understanding of what you are trying to do, you are enabling a button once the form input is valid. (correct me if i'm wrong)
You should being writing a function in the background to check and validate the the input data that the user is filling out. If all the data is valid, then enable the button. If not valid, disable it.
You can run this function every time there is an "onKeyUp" event that is attached to each form input element.

Watching input element's CSS class when using async validation doesn't work as expected

I've taken a bootstrap directive that watches all the input elements on a form and updates the CSS of its parent div to show validation errors in a Bootstrap way. The watch looks at the elements css class and if ng-invalid is present it adds has-error to the parent.
element.find('.form-group').each(function () {
var formGroup = $(this);
var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if (inputs.length > 0) {
inputs.each(function () {
var input = $(this);
scope.$watch(function () {
return input.hasClass('ng-invalid') && (!input.hasClass('ng-pristine') || form.$submitted);
}, function (isInvalid) {
formGroup.toggleClass('has-error', isInvalid);
});
});
}
});
The original directive was taken from an answer on S.O. I think the original answer derives from this Reconcile Angular.js and Bootstrap form validation styling but someone took it and expanded on it and I can't find their answer. It also takes more code from this show validation error messages on submit in angularjs to handle preventing the form being submitted but I'm omitting that for now
The directive works fine when using synchronous validators but when I use an async validator it gets the validation states mixed up. After making the field invalid, the watch fires but input.hasClass('ng-invalid') returns false. I'm at a loss about why it might happen.
I've created a plunkr here http://plnkr.co/edit/0wUUPdZc0fYN6euvsIMl?p=preview
One thing that could possibly be done here is to use child forms for each form group and if the child forms are invalid, then the parent form itself will not be valid.
Here's an example.
http://jsbin.com/luvegecalo/1

Javascript if statement not triggering 'true' statement

I have a multi-step form that relies on javascript to determine the options show in step 2.
The if statement should take the value of the email field and should show a specific option (div element) if the domain is #vip.co.uk and a set of general options (div element) if any other domain is used.
The form is working as it should but I seem to be seeing the general options for all email domains, the if statement doesn't appear to be working.
Below is the If statement:
function checkEmail(){
var email = document.getElementById('email').value;
var idx = email.lastIndexOf('#');
if (idx > -1 && email.slice(idx + 1) === 'vip.co.uk'){
document.getElementById('special').style.display = 'block';
document.getElementById('general').style.display = 'none';
}
}
document.getElementById("next").addEventListener("click", checkEmail);
Given the amount of code I have created a JS fiddle with the full form at http://jsfiddle.net/zsasvoo4/.
I'm keen to know what I am doing wrong.
Two things:
Open debug console and you will see that document.getElementById("next") returns undefined. There is no element with ID next. You could solve this by adding id="next" to the button.
If you are using jQuery it is more common to use $('#next') instead of .getElementById() methods. And, if you are using jQuery you could also select the button with $('[name=next]') if you don't want to change the markup. The full code to attach the event handler could be written as: $('[name=next]').click(checkEmail);

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

Is it a good practice to validate a form based on element's color?

I'm working on a form which has a validation script before submitting data.
Basically in all input fields, I have a function to test if the content of input is correct, triggered by 'onchange' event. If the content is 'invalid', the function will set the background of that input field to red.
function looseColorQty(t)
{
var n = t.value;
if(isNaN(n) == true || n < 0){
t.style.backgroundColor="red";
} else {
t.style.backgroundColor="";
}
}
Then when the user click 'submit' button, there's another script to check if this form can be submitted based on if any of the input fields is 'red'.
var canNotSubmit = 0;
function checkError(){
var fieldsToCheck = document.getElementsByTagName("input");
var fieldsQty = fieldsToCheck.length;
for(var i=0; i<fieldsQty; i++){
var checkTarget = fieldsToCheck[i].style.backgroundColor;
if( checkTarget == "red"){
document.getElementById("tips").className = "tipError";
document.getElementById("tips").innerHTML = "Please correct all RED fields before you submit.";
canNotSubmit = 1;
return;
}
}
}
It actually works but I just have a weird feeling that this validation is based on color. I wanna know if there's any drawback by doting so.
I think this is not a good idea.
Instead, if you're not using HTML5 field validation, I would attach (or change) an attribute on the field; for instance instead of setting t.style.backgroundColor="red" attach a data-validation="invalid" attribute, and then use your CSS to style it as a red background.
Base things on semantics (meaning) not on appearance.
Then you onsubmit handler can check for any data-validation="invalid" fields and issue messages based on those.
Don't forget to always validate again on the server after the submit, because you can't trust the client-side validation -- the data can always be tampered with after it has passed client validation.
I would add an additional classname to the element. Like value-is-invalid. Than you could check if the elements classname contains this class. You can also move your background-color: red; into this class in a css file. So you can seperate style from logic and change the style more easier later.
Like:
.value-is-invalid {
background-color: red;
}
As Stephen P pointed out you can't rely on client-side validation. always validate on server-side, too.

Categories