Regular expression

Discussion in 'JavaScript' started by Dwizzy, Jun 9, 2009.

  1. #1
    Hi, I am working on this Javascript program to write a form and I am trying to use regular expression for the name expression and I don't know why this is not working. Could someone pls tell me what is wrong this code?

    function validateForm()
    {
    var firstname = document.getElementById("f_name").value;
    var lastname = document.getElementById("l_name").value;
    var pcode = document.getElementById("p_name").value;
    var address = document.getElementById("add").value;
    var phone = document.getElementById("phone").value;

    var exp = validateFirstName(firstname);
    if(exp == null)
    {
    alert("no match");
    document.getElementById("_fname").style.color = "Red";
    }
    }

    function validateFirstName(txt)
    {
    var regex = /^[A-Z][a-z]+$/;
    return regex.match(txt);
    }



    O yeah and is there any software I can write Javascript in that isn't notepad or notepad++.. Something that shows me errors and Warnings....
     
    Dwizzy, Jun 9, 2009 IP
  2. Unni krishnan

    Unni krishnan Peon

    Messages:
    237
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    0
    #2
    Hi Dwizzy,

    The 'match' function that are using to compare regular expression, should be invoked as a method of string.
    Since you are using a regular expression(regex here) so you can try the 'test' or 'exec' method.
    Better using 'test' as it returns true or false, and i think it is what u need.
    For your info 'exec' returns an array when atleast a match is found, and else null.

    Hope this helps.
     
    Unni krishnan, Jun 9, 2009 IP
  3. Dwizzy

    Dwizzy Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Sorry, I am not sure I understand what you mean... You see my understanding of a regular expression is a string right... you can basically initialize it as an object or a variable...
     
    Dwizzy, Jun 9, 2009 IP
  4. clarky_y2k3

    clarky_y2k3 Well-Known Member

    Messages:
    114
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    108
    #4
    Find:-
    return regex.match(txt);
    Code (markup):
    Replace With:-
    return txt.match(regex);
    Code (markup):
     
    clarky_y2k3, Jun 10, 2009 IP
  5. Unni krishnan

    Unni krishnan Peon

    Messages:
    237
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    0
    #5
    Regular expressions can be created in two ways:

    1.Define it as an instance of the global RegExp object.

    2. simply assign it to a variable in literal form (i.e. /......./ )

    Hope this solves your query.
    Reply if still confusing.
     
    Unni krishnan, Jun 10, 2009 IP