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 3 of 3

Thread: validate input

  1. #1
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    806
    Thanks
    42
    Thanked 6 Times in 5 Posts

    validate input

    I need to check the input of a textarea. I require the cursor not to allow input of anything except "n" or "N" or "y" or "Y".

    I have this so far:

    Code:
    function validate() {
        var val = document.getElementById('textarea').value;
        if (/^\s*$/g.test(val)) {
            alert('Wrong content!');
        }
    }
    It checks for empty spaces I think.

    How can it check for yes or no? (y or Y or n or N)
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,732
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Code:
    <input type = "text" id = "textarea" size =  "1" maxlength = "1" onblur = "validate()">
    
    <script type = "text/javascript">
    function validate() {
    var val = document.getElementById('textarea').value;
    if (/[^yn]/gi.test(val)) {
    alert ('Wrong content!  You must enter y or n');
    document.getElementById('textarea').value = "";
    return false;
    }
    }
    </script>

    It is a bad idea to name an HTML field "textarea". And why a textarea if the only valid entry is y or n?


    Due to earlier signalling problems there are short-notice castrations in the Guildford area. - Train announcer at Wimbledon Station.
    Last edited by Philip M; 01-22-2013 at 07:32 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.

  • Users who have thanked Philip M for this post:

    tpeck (01-22-2013)

  • #3
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    806
    Thanks
    42
    Thanked 6 Times in 5 Posts
    Thanks Philip.

    I have changed it to an <input> with the id="done":

    Code:
    <input type="text" class="Format4" id="done" name="done" size="1" maxlength="1" value="N">
    It works!
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)


  •  

    Posting Permissions

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