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 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Form validate to check for characters other than letters

    Hi, I'm new to javascript and I'm trying to put a validation inside a function which checks if the name a user entered into the form contains anything other than letters and spaces. When I click out of the name field, it doesn't show the alert.

    Code:
    function isFilled(field) {
    
    var illegalCharacters = /[^a-z]/;
    if(field.value == null || field.value.length == 0 || !(isaString(field)))
    {
    alert("Please fill out your name"); //Checks for an empty field
    return false;
    }
    else if(illegalCharacters.test(field.value))
    {
    alert("Invalid name. The name contains illegal characters");
    return false;
    }
    return true; 
    }
    Any help on my issue would be greatly appreciated. Thank you in advance.
    Last edited by viciousmackerel; 02-21-2013 at 09:08 PM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    This will validate first and last names separately. If you want the user to enter his firstname and lastname in the same input box, you can use only one of the functions but you must allow a space as well as letters, hyphen and apostophe which are all valid characters in a proper name. (Jean-Paul O'Flangahan).

    A form field can never be null - only "" (blank).

    Code:
    <html>
    <head>
    
    <script type = "text/javascript">
    
    function check(form) {
    var fn = form.firstname;
    var fnv = form.firstname.value;
    fnv = fnv.replace(/\s+/g,"");  // strip all spaces OR
    //fnv = fnv.replace(/^\s+|\s+$/g,"");  // strip only leading and trailing spaces;
    //fnv = fnv.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    // convert whatever is entered into lower case but with a capitalised first letter
    fnv = fnv.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    form.firstname.value = fnv;  // write it back to the field
    if ((fnv == "Firstname") || (fnv.length < 2) || (/[^a-z\-\']/gi.test(fnv))) {  // only a-z hyphen and apostophe allowed in proper name
    form.firstname.value= "";  // clear the invalid field
    alert("Invalid characters or name too short!  Please enter your first name!");
    myfield = fn;  // note myfield must be a global variable
    setTimeout('myfield.focus();myfield.select();' , 10);  // to overcome bug in Firefox
    return false;
    }
    
    var ln = form.lastname;
    var lnv = form.lastname.value;
    lnv = lnv.replace(/\s+/g,"");  // strip all spaces OR
    //lnv = lnv.replace(/^\s+|\s+$/g,"");  // strip only leading and trailing spaces;
    //lnv = lnv.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    // convert whatever is entered into lower case but with a capitalised first letter
    lnv = lnv.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    form.lastname.value = lnv;  // write it back to the field
    if ((lnv == "Lastname") || (lnv.length < 3) || (/[^a-z\-\']/gi.test(lnv))) {  // only a-z hyphen and apostophe allowed in proper name
    form.lastname.value= "";  // clear the invalid field
    alert("Invalid characters or name too short! Please enter your last name!");
    myfield = ln;  // note myfield must be a global variable
    setTimeout('myfield.focus();myfield.select();' , 10);  // to overcome bug in Firefox
    return false;
    }
    
    alert ("You entered " + fnv + " " + lnv);  // for testing
    return true;
    }
    
    </script>
    </head>
    <body>
    
    <form  id = "myform" action="" onsubmit="return check(this)">
    <input id="firstname" name="firstname" type="text" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null" onblur="this.value==''?this.value=this.defaultValue:null">
    <input id="lastname" name="lastname" type="text" value="Last Name" onfocus="this.value==this.defaultValue?this.value='':null" onblur="this.value==''?this.value=this.defaultValue:null">
    <input type="submit" value="Submit">
    </form>
    
    </body>
    </html>

    Quizmaster: The English name for each of the days in the week ends in which letter of the alphabet?
    Contestant: D

    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.

  • #3
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    This will validate first and last names separately. If you want the user to enter his firstname and lastname in the same input box, you can use only one of the functions but you must allow a space as well as letters, hyphen and apostophe which are all valid characters in a proper name. (Jean-Paul O'Flangahan).

    A form field can never be null - only "" (blank).

    Code:
    <html>
    <head>
    
    <script type = "text/javascript">
    
    function check(form) {
    var fn = form.firstname;
    var fnv = form.firstname.value;
    fnv = fnv.replace(/\s+/g,"");  // strip all spaces OR
    //fnv = fnv.replace(/^\s+|\s+$/g,"");  // strip only leading and trailing spaces;
    //fnv = fnv.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    // convert whatever is entered into lower case but with a capitalised first letter
    fnv = fnv.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    form.firstname.value = fnv;  // write it back to the field
    if ((fnv == "Firstname") || (fnv.length < 2) || (/[^a-z\-\']/gi.test(fnv))) {  // only a-z hyphen and apostophe allowed in proper name
    form.firstname.value= "";  // clear the invalid field
    alert("Invalid characters or name too short!  Please enter your first name!");
    myfield = fn;  // note myfield must be a global variable
    setTimeout('myfield.focus();myfield.select();' , 10);  // to overcome bug in Firefox
    return false;
    }
    
    var ln = form.lastname;
    var lnv = form.lastname.value;
    lnv = lnv.replace(/\s+/g,"");  // strip all spaces OR
    //lnv = lnv.replace(/^\s+|\s+$/g,"");  // strip only leading and trailing spaces;
    //lnv = lnv.replace(/\s{2,}/g," ");  // Replace multiple spaces with one space
    // convert whatever is entered into lower case but with a capitalised first letter
    lnv = lnv.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    form.lastname.value = lnv;  // write it back to the field
    if ((lnv == "Lastname") || (lnv.length < 3) || (/[^a-z\-\']/gi.test(lnv))) {  // only a-z hyphen and apostophe allowed in proper name
    form.lastname.value= "";  // clear the invalid field
    alert("Invalid characters or name too short! Please enter your last name!");
    myfield = ln;  // note myfield must be a global variable
    setTimeout('myfield.focus();myfield.select();' , 10);  // to overcome bug in Firefox
    return false;
    }
    
    alert ("You entered " + fnv + " " + lnv);  // for testing
    return true;
    }
    
    </script>
    </head>
    <body>
    
    <form  id = "myform" action="" onsubmit="return check(this)">
    <input id="firstname" name="firstname" type="text" value="First Name" onfocus="this.value==this.defaultValue?this.value='':null" onblur="this.value==''?this.value=this.defaultValue:null">
    <input id="lastname" name="lastname" type="text" value="Last Name" onfocus="this.value==this.defaultValue?this.value='':null" onblur="this.value==''?this.value=this.defaultValue:null">
    <input type="submit" value="Submit">
    </form>
    
    </body>
    </html>

    Quizmaster: The English name for each of the days in the week ends in which letter of the alphabet?
    Contestant: D

    Thank you for your reply. The part of code which I needed in your example was the if statement containing /[^a-z\-\']/gi.test(fn). I put it into my own code in hope that it will give me an error message once I click out of the name field after entering in a number. Sadly it didn't work .. I've been scratching my head for the last hour and a half trying to get this to work with no avail.

    This is what I got now:
    Code:
    function isFilled(field) {
    
     if(field.value == "" || field.value.length == 0 || !(isaString(field)))
     {
       alert("Please fill out your name");
       return false;
      }
      else if(/[^a-z\-\']/gi.test(field.value))
      {
        alert("invalid");
    	return false;
      }
      return true; 
    }
    Here is the instructions I was given for this part of my project. Sadly, the lecturer hasn't covered a lot of my project so I'm left to do it myself.
    As each element is being entered, validate it when the user leaves the field element (onblur). The name should not be blank and only contain letters and spaces. Each mark should be a number in the range 0 – 100.
    Code:
    label for="name">Name</label>
    <input type="text" name="name" id="name" size="20"   pattern = "[A-Z][a-z]+( [A-Z][a-z]+)?" title="Please enter a name (Surname optional) with First Letter capitalised" onblur="isFilled(this)"
    Last edited by viciousmackerel; 02-21-2013 at 10:27 PM.

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Code:
    Enter your name <input type = "text" id = "username" onblur = "isFilled(this)">
    
    <script type = "text/javascript">
    
    function isFilled(field) {
    var val = field.value;
    val = val.replace(/^\s+|\s+$/g,"");  // strip leading and trailing spaces
    // no need for any other checks!
    if ((/[^a-z\-\'\s]/gi.test(val))  || (val.length <2)) {   // only letters hyphen apostrophe space allowed, must be at least two valid characters (Al, Jo etc.)
    alert ("Name too short, or invalid characters in username");
    field.value = "";  // clear the field
    field.focus();  // refocus on it
    return false;
    }
    return true; 
    }
    
    </script>
    It is essential to erase the leading and trailing spaces, as otherwise if the user enters just two (or more) spaces it will pass the validation.

    It is also a good idea to capitalise the name and write it back to the field - jOHn > John. Your instructions call for the user to do this, but it is best to enforce it programatically.

    Code:
    val = val.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    field.value = val;
    Last edited by Philip M; 02-21-2013 at 10:49 PM. Reason: typos

    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.

  • Users who have thanked Philip M for this post:

    viciousmackerel (02-21-2013)

  • #5
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Code:
    Enter your name <input type = "text" id = "username" onblur = "isFilled(this)">
    
    <script type = "text/javascript">
    
    function isFilled(field) {
    var val = field.value;
    val = val.replace(/^\s+|\s+$/g,"");  // strip leading and trailing spaces
    // no need for any other checks!
    if ((/[^a-z\-\'\s]/gi.test(val))  || (val.length <2)) {   // only letters hyphen apostrophe space allowed, must be at least two valid characters (Al, Jo etc.)
    alert ("Name too short, or invalid characters in username");
    field.value = "";  // clear the field
    field.focus();  // refocus on it
    return false;
    }
    return true; 
    }
    
    </script>
    It is essential to erase the leading and trailing spaces, as otherwise if the user enters just two (or more) spaces it will pass the validation.

    It is also a good idea to capitalise the name and write it back to the field - jOHn > John. Your instructions call for the user to do this, but it is best to enforce it programatically.

    Code:
    val = val.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()});
    field.value = val;

    Thanks a lot for your help! It's finally working!

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by viciousmackerel View Post
    Thanks a lot for your help! It's finally working!
    Glad to hear it! So long as you learn from the code you have been given and not just blindly copy/paste it.

    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.

  • #7
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Glad to hear it! So long as you learn from the code you have been given and not just blindly copy/paste it.
    I learned from it I used W3 schools to find out what each meta character and bracket was for and I knew the meaning behind the rest. I had to go off and learn most of the project myself as we have only been covering really basic java script in our practicals and lectures so far. We got given an assignment which contained a lot of stuff we didn't yet cover.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by viciousmackerel View Post
    I learned from it I used W3 schools to find out what each meta character and bracket was for and I knew the meaning behind the rest. I had to go off and learn most of the project myself as we have only been covering really basic java script in our practicals and lectures so far. We got given an assignment which contained a lot of stuff we didn't yet cover.
    People coming here say that quite often. I find it puzzling that students are expected to understand use stuff which has not been taught yet. You might as well do a home study course and save the tuition fees.

    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.

  • #9
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    People coming here say that quite often. I find it puzzling that students are expected to understand use stuff which has not been taught yet. You might as well do a home study course and save the tuition fees.
    In our practical classes, we do really basic stuff such as string manipulation. Here's two questions which have been asked in the previous 2 practicals..

    Prompt the user for their username. Get the first 3 characters (0 – 3) and output them, using substring.
    Output (using a loop) the numbers from 1 – 10 (inclusive) and output each numbers’ squared value, and square root.
    A lot more basic and simple than what we were tasked to do in our project, 80% of the project I had to go learn myself, while a lot of people aren't bothering with doing it since they haven't been taught it yet. I'm thinking about buying a java and java script book to help me out as the lecturers notes are really basic and don't contain a lot of information. It's can be rather annoying, since a lot of fees are being paid to the college and the lecturers are doing their job poorly.

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,910
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    At its very simplest:-

    Code:
    <script type = "text/javascript">
    
    var username = prompt("Please enter your name", "");  // prompts are considered obsolete.  You should use a textbox.
    username = username.replace(/[^a-z]/gi,"");  // strip all characters but letters
    username = username.substring(0,3);
    alert (username);  // alerts are regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
    
    for (var i =1; i<=10; i++) {
    document.write(i + "&nbsp&nbsp&nbsp&nbsp" +  i*i +   "&nbsp&nbsp&nbsp&nbsp" + Math.sqrt(i).toFixed(3) + "<br>");
    // document.write() is regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
    // the output ought properly to be presented in a table.
    }
    
    </script>

    Note that prompt(), alert() and document.write() are all considered obsolete.

    Output in a table styled with css:-

    Code:
    document.write('<table border="1" cellspacing="1" cellpadding="5">')
    for (var i =1; i<=10; i++) {
    document.write("<tr>" + "<td style='width:30px'>" + i + "</td> " + "<td style='width:40px'>" +  i*i +  "</td>" +  "<td style='width:50px'>" + Math.sqrt(i).toFixed(3) + "</td>" + "</tr>");
    // document.write() regarded as obsolete and should be used only for testing purposes.  Use DOM methods to display a message to the user.
    }
    document.write("</table>")
    .... since a lot of fees are being paid to the college and the lecturers are doing their job poorly.
    Yes, we see a lot of that here in this forum. Does your college teach other subjects such as medicine, law or French so incompetently, using antiquated techniques and long-outdated vocabulary? I would advise you to raise an official complaint.

    Curious that you are asked to use regular expressions which are normally considered quite advanced alongside obsolete methods such as prompt().

    I don't mind showing you solutions to your assignments provided that you study them and genuinely learn, and not just copy and paste.
    Last edited by Philip M; 02-22-2013 at 07:57 PM. Reason: Typos

    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.


  •  

    Tags for this Thread

    Posting Permissions

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