Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  99] [ 7]  / answers: 1 / hits: 19838  / 11 Years ago, thu, may 9, 2013, 12:00:00

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)


More From » forms

 Answers
107

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>

[#78327] Wednesday, May 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mathewb

Total Points: 535
Total Questions: 95
Total Answers: 96

Location: British Indian Ocean Territory
Member since Fri, Oct 15, 2021
3 Years ago
;