www.webdeveloper.com
Results 1 to 4 of 4

Thread: javascript problem, form validation

  1. #1
    Join Date
    Feb 2010
    Posts
    2

    javascript problem, form validation

    i am learning javascript, about the form validation.

    for the contact number part, the form allow user to key in "0123456789+-" these character only, i thought my code will work well, but i really cannot figure out what happen to my code.

    if the user let the contact number be blank, my code is working. so i think that 2 nested loop got some problem. thanks for help.

    function validContactNumber(contactNumber){
    validNumber="0123456789-+"

    if(contactNumber=="")
    return false




    for(i=0; i<contactNumber.length; i++){
    for(j=0; j<validNumber.length; j++)
    {
    a=validNumber.charAt(j)
    b=contactNumber.charAt(i)


    if(a!=b)
    return false

    }
    }
    return true

    }

  2. #2
    Join Date
    Feb 2010
    Posts
    12
    It seems you have a logic error in the nested loops. For example, it the contactNumber is 123 then it will check the first character in this case "1" against the first character of validNumber ("0") and since they are not equal it will return false and no further checks will be performed.You can try something like this:
    HTML Code:
    <pre>
    validNumber="0123456789-+"
    
    if(contactNumber=="")
    return false;
    
    for(i=0; i<contactNumber.length; i++){
    	valid = false;
    	for(j=0; j<validNumber.length; j++){
    		a=validNumber.charAt(j);
    		b=contactNumber.charAt(i);
    		
    		if(a==b)
    			valid = true;			
    	}
    	if (!valid)
    		return false;
    }
    return true;
    </pre>

  3. #3
    Join Date
    Feb 2010
    Posts
    2
    Thanks, ur code is working.

    i have some question, i saw some javascript contain ";" in the end of line, but some book dont write it. so, what is the differences?

    according to my code above, why the result always return as true instead of false? (for my html, i design as if it return false it will display the message using alert(), but if it return true, then the page will redirect into another page, and not display the alert()).

    moreover, got any software can check the syntax error of javascript?

    thanks again.

  4. #4
    Join Date
    Feb 2010
    Posts
    12
    The ; at the end of line is optional. But you have to have it in case you have more than 1 statement on the same line to separate them. However, it is considered a good programming practice to end each line with ;

    The good tool is Javascript Debugger (it is an add-on for Firefox that you have to install).

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles