loop to limit attempts at validation - javascript

I am trying to figure out a simple way to limit the amount of attempts on a field(s) through a while loop in javascript. Just doesn't seem to want to loop but the validation is still working. Here is the code I was trying to use:
function validateForm() {
x=document.forms["Form"]["name"].value;
var i=0;
var sum=0;
do {
sum += i;
i++;
}
while (i < 3)
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
Thanks in advance for any ideas.

You will have to store the variable outside of the function:
var numOfTries = 0;
function validateForm() {
if(++numOfTries > 3) {
alert('You have reached the maximum number of tries!');
location.replace("error_page.html"); // do something about it
}
x = document.forms["Form"]["name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}

Related

JavaScript: add alert message if name or password less than 6

try to add function in JS where alert box will show message Password or Username must be more than 6 :
Password :
Password must have atleast 6 characters
Username :
Username must have atleast 6 characters
So far I got function show alert if Pass or Username is NULL
JaveScript Code :
function validateForm() {
var x = document.forms["myForm"]["namapengguna"].value;
if (x == "" || x == null) {
alert("Nama must be filled out");
return false;
}
var x = document.forms["myForm"]["username"].value;
if (x == "" || x == null) {
alert("User must be filled out");
return false;
}
var x = document.forms["myForm"]["password"].value;
if (x == "" || x == null) {
alert("Pass must be filled out");
return false;
}
var x = document.forms["myForm"]["confirm_password"].value;
if (x == "" || x == null) {
alert("Confirm Pass must be filled out");
return false;
}
else {
alert('Application Has Been Registered');
location.assign("homeA.php");
}
}
but I couldn't figure out how can add alert message if name or password less than 6.
Any idea or solution are really appreatiate.
p/s: if my question is not good enough for you to understand, please tell me so I can improve it.
You can check string length by doing x.length. So:
if (x.length <= 6) {
// Do what you want
}
You may also want to make sure the user hasn't inputted any spaces at the start or end of the field.

Validating Radio entry

I have 2 address entries on my form. I also have 2 radio buttons to designate the "preferred" mailing address.
I'm attempting to validate these 2 and am not really sure if I'm doing it correctly. It seems to work if I have both addresses filled but I can't seem to get it to validate correctly if one of the addresses isn't filled.
Here's the javascript that does the validation:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
$("#" + prefs[i]).prop('checked', false);
$("#MailPrefBusi").validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
$("#MailPrefBusi").validationEngine({promptPosition : "bottomRight", scroll: true}).validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
}
return true;
}
I'm using jQueryValidationEngine but it also doesn't correctly validate them. I only use it to show the validation error for these fields.
Here is the criteria:
If the MailPrefBusi is checked, then the BusinessAddress1 must be filled in.
If the MailPrefHome is checked, then the HomeAddress1 must be filled in.
If no MailPrefxxx is checked, show error. If no xxxAddress1 is filled, Show error.
It looks like your second if statement if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) { is returning false when you don't want it to. You should be able to accomplish what you want using this:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
// enhanced validation function call here
return false;
}
}
//if the user hasnt checked anything, you can remove this if the form should validate without the user having to set a radio button
if(!$("#MailPrefBusi, #MailPrefHome").is(":checked")) {
// enhanced validation function call here
return false
}
return true;
}
You can see it working at this JS Fiddle: https://jsfiddle.net/h0vj9r35/
Hope that helps!
If you are trying to figure out whether the corresponding fields are filled based on checkbox values in a scenario where you have n no. of checkboxes and fields and would like to avoid hardcoding of values, you may use the following:
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
var allEmpty = false;
var valueError = ""
for (i = 0; i < 2; i++)
{
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
if(!$("#"+prefs[i]).is(":checked"))
valueError += prefs[i] + "," ;
else if($("#"+field[i]).val() == "")
valueError += field[i];
allEmpty = true;
}
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "")
{
$("#" + prefs[i]).prop('checked', false);
allEmpty = false;
alert("Need to enter " + field[i]);
return false;
}
if((i == 1) && allEmpty)
{
alert("You need to select " + valueError);
return false;
}
}
return true;
http://jsfiddle.net/n0303qd6/1/

js syntax passing name elements form validation

I just need help on how to pass multiple 'name' elements in my function that validates a form submission.
I have this and works fine.
var x = document.forms["myForm"]["FirstName"].value;
if (x == null || x == "")
{
alert("asdf");
return false;
}
tried this but didnt work.
var x = document.forms["myForm"]["FirstName"+"LastName"].value;
if (x == null || x == "")
{
alert("asdf");
return false;
}
Any help with the syntax on how to do so would be appreciated.
What you are trying makes no sense.
var x=document.forms["myForm"]["FirstName"+"LastName"].value;
would get the value from an element called FirstNameLasteName.
So you probably meant this:
var x=document.forms["myForm"]["FirstName"].value + document.forms["myForm"]["LastName"].value;
You meant this:
var x=document.forms["myForm"]["FirstName"].value + " " +
document.forms["myForm"]["LastName"].value;
if (x==null || x=="")
{
alert("asdf");
return false;
}

JavaScript Form onkeyup Validation Errors

Not getting any errors in Aptana, so something I'm doing probably doesn't make sense. Basically, I am getting the value from a form and checking it against a regex. If the new checked variable isn't empty then I output to a different div that it is valid, and that it is not valid if the variable is empty.
<script type="text/javascript">
var age_regex=/(1[8-9]|2[0-9]|3[0-5])/;
var error_box= document.getElementById('error_box');
function checkAge(x){
var age = document.getElementById(x).value;
var checked_age = test.age_regex(age);
if (checked_age.value != "")
error_box.innerHTML = "Correct!";
else {
error_box.innerHTML = "Incorrect!";
}
}
</script>
Why regex for age ? How about this :
function checkAge(str) {
if(parseInt(str, 10) != str) {
return false;
}
if(parseInt(str, 10) < 18 || parseInt(str, 10) > 35)
{
return false;
}
}

Form Validation - How to use If and Else If

I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...

Categories