Reputation: 1077
I'm hoping someone can help me with a bit of validation, I'm taking the value of a form input as a string. I need to validate this against a couple of rules, so it can become a table name. I can do them individually but I've no idea how to put it together. The input (tempName) needs to:
1.
newName = tempName.replace(' ', '_')
2.
var regex=/^[0-9A-Za-z]+$/; //^[a-zA-z]+$/
if(regex.test(tempName)){
tempName = newName
return true;
}
else {
alert("Only letters + numbers allowed - no special characters or spaces.")
return false;
}
3.
if (tempName.length < 25) {
newName = tempName
}
else {
newName = tempName.substr(0,25);
}
Apologies for asking something so simple but I haven't really worked with javascript properly for a few years and I'm having trouble with nested if statements and setting conditions.
Help would be greatly appreciated.
Thanks.
Upvotes: 3
Views: 198
Reputation: 224913
if(/^\w{,25}$/.test(name = name.replace(/\s/g, '_'))) {
// It's valid.
}
Is probably what you want.
Edit: If you want to truncate to 25 characters, it's:
if(/^\w+$/.test(name = name.replace(/\s/g, '_').substring(0, 25))) {
// It's valid.
}
Upvotes: 5
Reputation: 18786
Well the first two you can put together.
newName = tempName.replace(" ", "_").replace(/\W/g, "");
But then I'd check for the length of the remaining string after the replaces to make sure I don't get a index out of range.
if(newName.length > 25) {
newName = newName.substring(0, 25);
}
Upvotes: 1
Reputation: 779
Sounds like you just need to drop most of that in a JavaScript function block.
function validateTableName(tempName)
{
var newName='';
your code here...
return newName;
}
HTH...
Upvotes: 1