Trying to validate form - javascript

Trying to learn JavaScript, makin decent progress I guess, but I'm stuck at validating a form, tried to see if anybody has the same problem, search didn't turn anything up. So would you please help me?
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
else {
alert("Password okay!");
}
}
submitbtn.onClick = validate();

It is not obvious where you call this - I have wrapped it in a window.onload
you do not access the button correctly. Either of
document.forms[0].submitbtn
document.getElementById("submitbtn") or
document.getElementsByName("submitbtn")[0] will work depending on how you name or ID the button HOWEVER do not assign onclick handlers to submit buttons, instead assign submit handler to the form
there is no point of testing for a single space since that is less than 6 chars anyway.
&& is AND, you mean || OR
onclick must be all lowercase.
You assign the onclick to the result of validate instead of validate
You do not stop the submission
I have taken the trim from here
and I assume the form has ID="form1"
window.onload=function()
document.getElementById("form1").onsubmit = validate;
}
if(typeof String.prototype.trim !== 'function') { // let's help older IEs
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
function validate() {
var minlength = 6;
var pw = document.getElementById('psswrd');
if (pw.value.length < minlength || pw.value.trim() == "") {
alert("Password not valid");
pw.focus();
return false;
}
return true; // allow submission
}

var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
}
else {
alert("Password okay!");
}
}

You have a few problems here.
1) pwlength.length won't get you very far. pwlength is equal to an html object, not the value of an html object. Change the actual variable to the following and you should get the correct results:
var pwlength = document.getElementById('psswrd').value;
2) Before the else part of your if ... else statement, you need to end the if statement by closing it with a curly bracket (}). Change that part to the following:
} else {
3) Your validation to check and see if the length == invalid is odd. Double check that and get rid of it.
4) Your onclick event needs to look something like this:
submitbtn.onclick = function(){ validate() };
Notice: lowercase event keyword and function() { ... }; wrapped around the function you want to run.

Related

What does "/^\s*$/" mean in this javascript?

I have this javascript that works well in my PDF form to set a field as required if another field contains data. However, I want to have it ignore a value of "0.00" for the test. But I do not know what /^\s*$/ means let alone how to alter the script for my condition.
var rgEmptyTest = /^\s*$/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
Thank you!
In your piece of code there is a function that uses regex
A javaScript regExp reference for you.
Thanks #j08691 for the link that explains and let you test the regex used (regexr.com/3rf9u).
You can change your code like this to make a logical exception
var rgEmptyTest = /^\s*$/;
var rgTest = /0.00/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t) || rgTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
I guess it should work
\s means space
* Means any number
" " This is empty
" " This too
I think I got this to work:
var rgEmptyTest = /^\s*$/;
var rgTest = /^[0\.00]$/;
// t is the value to be tested and f is the field to set accordingly
function testMyField (t, f) {
if (rgEmptyTest.test(t) || rgTest.test(t)) {
this.getField(f).required = false;
} else {
this.getField(f).required = true;
}
}
Thank you #Higor Lorenzon and #j08691!

Javascript: How do you invoke a function which has parameters

As part of a validate onsubmit function, I wish a function isFilled(var str) to be invoked. However, it is failing to be invoked successfully and as a result the validateForm() function is terminated prematurely.
<script type = "text/javascript">
function validateForm(){
...
alert(isFilled("bla bla bla"));
...
}
function isFilled(var str){ // checks that the given string isn't empty
if(str == "" || str == " "){
return false;
}else{
return true;
}
}
</script>
Furthermore I am not being informed by the browser's console of the error. Should I wrap my code in try/catch statements? If so, how?
Declaring function arguments is incorrect in javascript. Corrected code:
function isFilled(str){ // checks that the given string isn't empty
if(str == "" || str == " "){
return false;
}else{
return true;
}
}
You're trying to declare a variable in a function parameter. Just give it a parameter name
str can be called whatever you want it to be:
function isFilled(parameter){ // checks that the given string isn't empty
if(parameter == "" || parameter == " "){
return false;
}else{
return true;
}
}

"return false;" for form submission is not working

"return false;" for form submission is working for the rest of my code, just not this section. Any ideas why?
function checkForm() {
$("select[name*=lic_company]").each(function() {
if($(this).val() != '') {
var i1 = $(this).parent("td").next("td").children("select");
var i2 = i1.parent("td").next("td").children("input");
var i3 = i2.parent("td").next("td").children("input");
if(i1.val() == '') {
i1.parent("td").addClass("formErrorTD");
i1.addClass("formError");
alert("You must enter a state for this license");
return false;
}
if(i2.val() == '') {
i2.parent("td").addClass("formErrorTD");
i2.addClass("formError");
alert("You must enter an expiration date for this license");
return false;
}
if(i3.val() == '') {
i3.parent("td").addClass("formErrorTD");
i3.addClass("formError");
alert("You must enter a license number for this license");
return false;
}
}
});
}
and it's being called by
$("#addAgentForm").submit(checkForm);
You are calling return false; within a closure that is an argument passed to .each. Therefore, .each is capturing the return false;. To get around this you need need to have a boolean flag that holds the state of the form:
function checkForm() {
var okay = true;
$("select[name*=lic_company]").each(function() {
...
return okay = false;
...
});
return okay;
}
And everything will work fine.
Your return false statements are inside the anonymous function passed to .each(), so only return a value from that function, not the entire call to checkForm().
If I had to guess, it's because you're returning from the function passed to your each call, meaning all you're really doing is exiting your each function while your main validation function finishes without a hitch.

Javascript check multiple textbox for numeric

I am checking numeric value for one textbox like this:
function validateNumeric() {
var old = document.getElementById("tbNum").value;
var new = old_val.replace(/^\s+|\s+$/g,"");
var validChars = '0123456789';
for(var i = 0; i < new.length; i++){
if(validChars.indexOf(new.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
document.getElementById("tbNum").value = new;
return true;
}
I want to use the same function and check numeric value for other text boxes that requires numeric value. How can I pass value of tbID, tbDiscID, as well as above and return true before submitting the form.
I am not sure what you mean by tbId and tbDiscID, but to do this in plain JavaScript, you can generalize this solution by traversing JavaScript's arguments object, which lets you pass in any variable number of arguments to your function. This will help you take in the IDs you need. Your new solution would look something like the following:
function validateNumeric() {
for (var arg in arguments) {
var id = arguments[arg];
var old = document.getElementById(id).value;
var new = old_val.replace(/^\s+|\s+$/g,"");
var validChars = '0123456789';
for(var i = 0; i < new.length; i++){
if(validChars.indexOf(new.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
document.getElementById(id).value = new;
return true;
}
}
Then invoke it like:
validateNumeric("myTextbox1", "myTextbox2", ..., "myTextboxN");
Where myTextBox1 ... myTextBoxN are the IDs of your textboxes.
use parameter for the function, for using it on different elements
validateNumeric(value) {
use the onsubmit parameter on the form tag to call a validation
<form name="myForm" action="dosomething.php" onsubmit="return validateForm()"
write your validate function with calls for all elements
function validateForm() {
if (!validateNumeric(document.getElementById("tbNum"))) {
return false;
}
...
return true;
would be one way..
edit
forgot the check within the validateForm method

Return from inner function in JavaScript?

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.
required_fields.forEach(function(field) {
if (field.val() == '')
{
field.addClass('field-highlight');
return false;
}
else
{
field.removeClass('field-highlight');
}
});
// I want to return to here from the return false point
How can I structure this differently to do what I want?
Just use a variable to keep track of the validation:
var is_valid = true;
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
is_valid = false;
return false;
} else {
field.removeClass('field-highlight');
}
});
return is_valid;
Or, you can just use the field-highlight class as well:
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
return false;
} else {
field.removeClass('field-highlight');
}
});
return $('.field-highlight').length == 0;
use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form
It sounds like you want to do the following
Update the elements with the field-highlight class based on whether or not they have a value
Block the form submission if any are empty
If so then try the following
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.
If your required_fields is a jQuery object, you could just do this:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
Or perhaps more efficient like this?
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop

Categories

Resources