Javascript Field Validation - javascript

I have three fields ForteID, disposition and Cancel_Disposition. Right now I have this code in my javascript and it works:
function validateForteID(){
if(document.csform.ForteID.selectedIndex==0)
{
alert("Please select your Forte ID.");
document.csform.ForteID.focus();
return false;
}
if(document.csform.disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.disposition.focus();
return false;
}
if(document.csform.Cancel_Disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}
return true;
}
What I am looking to do and not exactly sure how to do it, but if the field Disposition is either LOC or Backout, I then want it to do this part of the code:
if(document.csform.Cancel_Disposition.selectedIndex==0)
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}
But only if the disposition is LOC or Backout. Let me know if there I need more explanation, thank in advance!

var cancel_disposition_value = document.csform.Cancel_Disposition[document.csform.Cancel_Disposition.selectedIndex].value;
if(cancel_disposition_value=='LOC' || cancel_disposition_value=='Backout')
{
alert("Please select a disposition.");
document.csform.Cancel_Disposition.focus();
return false;
}

Related

I have 2 forms here,after submitting validatting the 1st one, how can I move to the 2nd to validate?

window.onload=alert("please,Sign Up first");
window.onload=pageload;
function pageload() {
var signup=document.getElementById("signup");
signup.onsubmit=signupp;
}
function signupp(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if (st=="First name" || st=="") {
alert("please enter your first name");
return false;
}
else if (ls=="Last name" || ls=="") {
alert("please enter your last name");
return false;
}
// what should i type here to move to loginn function ?
}
function loginn(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if(username==""){
alert("please enter your username or your phone number");
return false;
}
if(password==""){
alert("please enter your password");
return false;
}
}
You can set the login wrapper div via CSS to:
#loginform{display:none;}
And then after registration set via JS to:
var loginform=document.getElementById("loginform");
loginform.style.display = 'block';

Javascript Email validation that allows a null value

I have this on submit function that checks for the email field to have a properly formatted address. Works fine. However, I want the field to allow a null value as this particular input is optional and not required. I know this should be simple, Im missing the obvious. Someone point me in the right direction...
EDIT: Providing the entire form validation this time. As every time I just replace the email portion its breaking other pieces....
function validateSMSForm()
{
if (SMSForm.PID_Form.value.length < 4)
{
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.prefix.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.line.value.length < 4)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
<!-- EMAIL VALIDATION HERE
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.emailaddress.value))
{
return (true)
}
alert("Please enter a valid email address")
return (false)
-->
}
Add a check for empty/null string first:
if ((!form.emailaddress.value) || (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(form.emailaddress.value))) {
//handle valid e-mail
} else {
//handle invalid e-mail
}
Like this
Assuming
<form onsubmit="return validateSMSForm(this)">
JavaScript:
function isEmail(str) {
return !str || /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,})+$/.test(str);
}
function validateSMSForm(SMSForm) {
if (SMSForm.PID_Form.value.length < 4) {
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3 ||
SMSForm.prefix.value.length < 3 ||
SMSForm.line.value.length < 4) {
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (!isEmail(SMSForm.emailaddress.value)) {
alert("Please enter a valid email address")
return false; //
}
return true; // allow submission
}
var email = form.emailaddress.value;
if (!email){ return true } // this what your looking for?
if (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(email))
{
return (true)
}
alert("Please enter a valid email address")
return (false)

Why do these alerts multiply?

OK, i have a couple of inputs. I have this code to validate them.
$("#form1").submit(function(){
var isFormValid = true;
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your First Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your Last Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Select Your Volunteer Choice");
return isFormValid;
});
For some reason, i get a message after a message. What i was aiming for is that it only show me the next field that has not been field out, not all of them at the same time. If you have a question, please comment, it is hard to explain....do not down vote until you give me a chance to better explain.
​
Here is how to simplify your code, and make it work like intended.
First, since you use the same method to validate all the fields, wrap that in a function instead of repeating the code:
function isFieldEmpty(jQuerySelector) {
return $.trim($(jQuerySelector).val()).length == 0
}
Second, use a single submit handler to check everything, and return false if any field does not pass validation:
$("#form1").submit(function(){
if(isFieldEmpty('#first_name')) {
alert("Please Enter Your First Name");
return false;
}
if(isFieldEmpty('#last_name')) {
alert("Please Enter Your Last Name");
return false;
}
if(isFieldEmpty('#dropdown')) {
alert("Please Select Your Volunteer Choice");
return false;
}
// Will return true only if all fields passed
return true;
});
I'm not familiar with JQuery but I think what is happening is your are binding 3 functions to your form, which means they all get called
when you want to do is create 1 function validate that calls your sub validations functions.
also I would recommend you change your sub validation methods to return the message instead of a boolean, this way you can display all the errors in 1 alert.
You have multiple alerts because you bind different functions to the submit event of the form: each one checks a different field and fires an alert if the field is empty.
You need to move the three validation steps in only one function and bind that function to the submit event.
Something like:
$("#form1").submit(check);
function check() {
var isFormValid = true;
var errors = array();
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your First Name");
}
});
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your Last Name");
}
});
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Select Your Volunteer Choice");
}
});
if (!isFormValid) {
var errorMsg = "";
for (var i = 0; i < errors.length; i++) {
errorMsg += errors[i] + "\n";
}
alert(errorMsg);
}
}
This is because of the redundancy on your code, same function, same identifier, same logic, same event handler, useless each with an id selector.
The only thing different are the subjects. Here is my suggestion.
$("#form1").submit(function(){
var errors = [];
if($("#first_name").val().length == 0){
errors.push("Please Enter Your First Name");
}
if($("#last_name").val().length == 0){
errors.push("Please Enter Your Last Name");
}
// and so on
if(var isFormValid = errors.length > 0) {
alert('you have errors');
//errors contains all the error message if you need them
}
return isFormValid;
});

how do i put the following in a for loop

I would like to put the following in a for loop but i am having difficulties. Any help would be appreciated
$("input:submit").click(function(){
if (!$("input[name=attendance1]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance2]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance3]").is(":checked")) {
alert('Please select preference');
return false;
}
});
});
I have tried:
for($i=1; $i<=3; $i++)
{
$("input:submit").click(function(){
if (!$("#food" + $i).is(":checked")) {
alert('Please select preference');
return false;
}
});
});
First fix:
alert('Please select preference);
with
alert('Please select preference');
Then if you want to loop:
for (var i = 0; i < 3; i++) {
if (!$("input[name=attendance" + i + "]").is(":checked")) {
alert('Please select preference');
return false;
}
}
Or better yet use jQuery's startsWith selector:
if (!$('input[name^="attendance"]').is(":checked")) {
alert('Please select preference');
return false;
}
Example
You're missing a closing single quotation mark on all 3 alert statements.
I generally use a class name on my DOM elements when I want to do something like this. That makes it easier to iterate through the elements using .each(). I was not aware of the startsWith selector mentioned above, but it does look a bit cleaner than my method.
<!-- DO STUFF -->
<input name="attendance1" class="my-unique-class-name" />
<input name="attendance2" class="my-unique-class-name" />
<input name="attendance3" class="my-unique-class-name" />
<!-- DO STUFF -->
<script type="text/javascript">
$("input:submit").click(function(){
var valid = true;
$("input.my-unique-class-name").each(function (el) {
if ( ! $(el).is(":checked") ) {
valid = false;
}
});
if ( ! valid ) {
alert('Please select preference');
return false;
}
});
</script>
Here's my take on it. it has the advantage of you listing down in an array what names you want checked, regardless what names they are
//jQuery '.on()' for versions 1.7+
$("input:submit").on('click', function() {
//assume valid unless found otherwise
var valid = true;
//add the input names you want to verify
var nameList = [
'attendance1',
'attendance2',
'attendance3'
];
//loop through names
for (var i = 0; i < nameList.length; i++) {
var checked = $('input[name="'+nameList[i]+'"]').is(':checked');
if (!checked) {
alert('Please select a preference');
//mark false when something wrong found
valid = false;
}
}
//check if validity persisted
if(valid){
//do something
}
//prevent default actions
return false;
});​

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories