Regular expression on textarea

16,559

To validate line by line, I'd use the split function to turn each line into an array. Then, loop through the array and run your RegEx on each line. That way, you can report exactly what line is invalid. Something like this:

<textarea id="ITSWUsers"></textarea>
<button onclick="Validate()">Validate</button>

<script>
  var usernamecheck = /^[A-Za-z0-9]{5,1000}\.[A-Za-z0-9]{5,1000}$/;

  function Validate()
  {
    var val = document.getElementById('ITSWUsers').value;
    var lines = val.split('\n');

    for(var i = 0; i < lines.length; i++)
    {
      if(!lines[i].match(usernamecheck))
      {
        alert ('Invalid input: ' + lines[i] + '.  Please write the usernames in the correct format (with a full stop between first and last name).');
        return false;
      } 
    }

    window.alert('Everything looks good!');
  }
</script>
Share:
16,559
Maff
Author by

Maff

Updated on June 07, 2022

Comments

  • Maff
    Maff almost 2 years

    I'm having a bit of trouble validating a form I have, I can check for only letters, numbers and a full stop ("period") in a single text input, but I can't for the life of me get it to work at all on a textarea field.

    in my validation I have this:

    var usernamecheck = /^[A-Za-z0-9.]{5,1000}$/; 
    

    the validation I've tried that doesn't work on the textarea ($ITSWUsers) is:

    if(!document.all.ITSWUsers.value.match(usernamecheck))
                    {
                    alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
                    return false;
                    }
    

    however, the following on a 'input type="text"' works just fine on the same form

    if(!document.all.SFUsersName1.value.match(usernamecheck))
                    {
                    alert("Usernames can only contain letters, numbers and full stops (no spaces).");  
                    return false;  
                    }  
    

    I need it to validate usernames, 1 name per line e.g.

    John.smith
    Peter.jones1
    

    these are both OK but the following wouldn't be:

    John Smith
    David.O'Leary
    3rd.username
    

    any help/pointers with this would be greatly appreciated (I only know basic html/php/javascript)