Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Nov 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    JavaScript indexOf issue

    Good Evening ,

    I have the following fuction. I'm still very new to JavaScript so forgive the code, I'm sure there are better ways of doing this.

    Code:
    function ValidateFirstName() {
        var FirstName = document.getElementById("FirstName").value;
        var FistNameValid = false;
        var nChars = "012345689";
        var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
        var FirstNameLength = FirstName.length;
        
        if (FirstName.indexOf(nChars) != -1) {
            alert("First Name has a number in it. Please Remove any numbers");
            return; 
        }   
        else if (FirstName == null || FirstName =="") {
            alert("Please Enter your First Name it is blank.");
            return;
        }
        else if (FirstNameLength > 50) {
            alert("Please Enter a First Name Less than 50 Characters. There are Currently " + FirstNameLength + " characters");
            return;
            }
        else if (FirstName.indexOf(iChars) != -1) {
            alert("First Name has Special Characters. \nThese are not allowed.\n");
            return;
        }
        else {
            FistNameValid = true;
        }
        //alert("First Name = " + FirstName);
        alert("Number Index = " + FirstName.indexOf(nChars));
        alert("Invalid Index = " + FirstName.indexOf(iChars));
        //ValidateLastName();
    
    }
    My Alerts for the indexes are always -1 even when I put the characters from the string in. Can someone explain what I'm doing wrong ?
    Last edited by ZMike; 11-22-2012 at 06:51 PM.

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    string1.indexOf(string2) will try to find the full string2 (all of its characters in the same order) inside of string1. This is certainly not what you want to achieve. You want to make sure that there is no numeric and no special character in string1.

    Code:
    if(/\d/.test(FirstName) || /[!@#\$%\^&\*\(\)\+=\-\[\]\\';,\.\/{}\|\":<>\?]/.test(FirstName) {
       // FirstName contains numbers or special characters
    }

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    indexOf( ) will only find a match if *EVERYTHING* used as the argument to indexOf( ) is found in the string you are searching.

    So if you do something like:
    Code:
       var name = "John $%";
       var where = name.indexOf("!@#$%^&*()+=-[]\\\';,./{}|\":<>?");
    then where will *always* be -1.

    *ONLY* if you had something like
    Code:
       var name = "John !@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    would indexOf( ) be able to find *ALL* of that stuff you are looking for.

    If you insist on using slow and ugly indexOf( ) for something like this, you must test the characters ONE AT A TIME.

    So you would need ugly code something like:
    Code:
        var firstNameValid = true;
        for ( var c = 0; c < iChars.length; ++c )
        {
            if ( firstName.indexOf( iChars.charAt(c) ) >= 0 )
            {
                firstNameValid = false;
                break; // out of the for loop
            }
        }
    ************

    But you are working WAY too hard.

    You don't need/want indexOf(). Learn to use REGULAR EXPRESSIONS.

    Code:
        var validName = /^[a-z]{2,49}$/i;
        if ( validName.test( firstName ) )
        {
            alert("First name must consist of 2 to 49 letters, only.");
            return false; 
        }
    Presto. No other validation needed.

    In fact, you can actually do it even shorter:
    Code:
        if ( firstName.match( /^[a-z]{2,49}$/i ) == null )
        {
            alert("First name must consist of 2 to 49 letters, only.");
            return false; 
        }
    EDIT: DevNull beat me to it, but I actually like my version a tad better if, indeed, you are look for a standard first name that consists only of letters.

    I suppose you might find a person with a hyphenated first name: "John-boy", in which case you could expand my expression a bit:
    Code:
        if ( firstName.replace(/\-/g,"Z").match( /^[a-z]{2,49}$/i ) == null )
        {
            alert("First name must consist of 2 to 49 letters, only.");
            return false; 
        }
    Last edited by Old Pedant; 11-22-2012 at 07:25 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    ZMike (11-22-2012)

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    A proper name may contain (only) letters, hyphen and (especially in family name) apostrophe. Perhaps also a space. Lots of names are hyphenated - Mary-Lou etc.

    Code:
    if (/[^a-z\-\']/gi.test(firstName)) {
    // error message;
    return false
    }
    var FirstName = document.getElementById("FirstName").value;

    It is strongly not advised to use the same name for an HTML element and a Javascript variable.

    var FistNameValid = false;
    FistNameValid = true;



    else if (FirstName == null || FirstName =="") {

    A form field value cannot be null. Only "" (blank).

    BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.
    Last edited by Philip M; 11-22-2012 at 08:17 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,166
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Actually, my hack of replacing the hyphen with Z was just plain silly.

    But Philip's solution has the same problem mine has: The user could enter a name of just "----" and it would be deemed acceptable.

    Probably what is really needed is /^[a-z]+([ \'\-][a-z]+)*$/i and then check for the length separately.

    That will still allow some silly names: O'M-G or r e a l l y but at least it requires that the name start and end with a letter and that the other allowed characters (space, apostrophe, hyphen) appear in the middle.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    New to the CF scene
    Join Date
    Nov 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Old Pedant,

    I really liked your code choice. I konw that I'm not going to catch every scenario but I just want to validate most. Here is now what I have :

    Code:
    function ValidateFirstName() {
        var vFirstName = document.getElementById("FirstName").value;    
        var ValidFirstName = /^[a-z]{2,50}$/i;
    
        if (ValidFirstName.test(vFirstName)==false){
            alert("First name must consist of 2 to 50 letters, only.");
            return false;
        }
        else {
            ValidateLastName();
        }
    }
    
    function ValidateLastName() {
        var vLastName = document.getElementById("LastName").value;
        var ValidLastName = /^[a-z]{2,50}$/i;
    
        if (ValidLastName.test(vLastName) == false) {
            alert("Last name must consist of 2 to 50 letters, only.");
            return false;
        }
        else {
            ValidateEmail();
        }
    }
    
    function ValidateEmail() {
        var vEmail = document.getElementById("Email").value;
        var ValidEmail = /\S+@\S+\.\S+/;
    
        if (ValidEmail.test(vEmail) == false) {
            alert("Please Enter a Valid Email Address");
        }
        else {
            alert("Email address " + vEmail + " passed validation.");
        }
    }
    I'm still doing som reading. This portion is part of an assignment.

    Starts with a letter
    Contains 1 and only 1 @
    Contains a minimum of 1 period after the @
    Contains at least 1 character between the @ and the period
    Ends with a domain extension ( com, org, edu, etc...,) – needs to have the minimum number of characters (2 for cc or tv) and does not exceed the maximum number of characters (research the longest domain extension) for a domain extension and is all letters.
    Does not include any illegal characters (research this)

    From what I found .museum is one of the longest. I really appriciate the feedback thus far. I had read on other sites that the indexOf was one of the better ways. but I MUCH prefer the solution given.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,618
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by ZMike View Post
    I'm still doing som reading. This portion is part of an assignment.

    Starts with a letter
    Contains 1 and only 1 @
    Contains a minimum of 1 period after the @
    Contains at least 1 character between the @ and the period
    Ends with a domain extension ( com, org, edu, etc...,) – needs to have the minimum number of characters (2 for cc or tv) and does not exceed the maximum number of characters (research the longest domain extension) for a domain extension and is all letters.
    Does not include any illegal characters (research this)
    There are a lot less illegal characters than the person who set you that assignment thinks there are given the other constraints they gave you.

    The part of the email address before the @ can be contained in quotes in which case just about any character can be included there. Without the quotes only letters, numbers underscores any hyphens are allowed

    The part after the @ can either be a domain name or an IP address enclosed in []

    So "@"@[127.0.0.1] is a valid email address that would not passmost of the rules you have been told to apply.

    For the subset of valid email addresses you have been asked to allow a significantly shorter regular expression is needed than what you would need if you were going to validate for any valid email address.

    .travel and .museum are currently the longest top level domains but applications are currently open so anyone can currently apply for their own top level domain of whatever they like provided no one else objects (for example two South American comuntries have objected to .amazon being given to a company). Ao if a company called "Double Alphabet" were to apply for the top level domain .abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz they could possibly get that - the maximum length of the entire domain name including the dots is 63 so they would only be able to have up to ten characters before the dot in that case. So allowing for one character before the dot the longest possoble top level domain would be 61 characters even though the longest currently in use is only 6.

    This should give you a start on creating a regular expression that matches the criteria for the assignment.

    The following first tests the maximum lengths of the two parts of an email address and then uses a regular expression will will allow any valid email address and reject any invalid ones - but of course 99.999%+ of valid email addresses don't actually exist and there is no way form JavaScript to tell if a valid email address actually exists - the only way to really test that is to send an email to the address and ask for and receive a response. If you examine it closely enough you should be able to work out what characters are and are not valid in email addresses.

    Code:
    validateEmail = function(email) {var e = (email+'@').split('@'); if (e[0].length > 255 || e[1].length > 63) return false; return !email.search(/^[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*@[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*|(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[^()<>@,;:".\\\[\]\x80-\xff\000-\010\012-\037]*(?:(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[^()<>@,;:".\\\[\]\x80-\xff\000-\010\012-\037]*)*<[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:@[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*(?:,[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*@[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*)*:[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)?(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*@[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:\.[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])[\040\t]*(?:\([^\\\x80-\xff\n\015()]*(?:(?:\\[^\x80-\xff]|\([^\\\x80-\xff\n\015()]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015()]*)*\))[^\\\x80-\xff\n\015()]*)*\)[\040\t]*)*)*>)$/);}
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

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