I want to enforce that
How do I restrict the two rules in javascript?
Below is my code (jsp) for username regex. But it's not working properly.
function validateForm(){
var nameRegex = /^[a-zA-Z\-]+$/;
var validfirstUsername = document.frm.firstName.value.match(nameRegex);
if(validUsername == null){
alert("Your first name is not valid. Only characters A-Z, a-z and '-' are acceptable.");
document.frm.firstName.focus();
return false;
}
}
Thanks!
1) Validate the username field The following checkUsername() function uses: The isRequired() function to check if the username is provided. The isBetween() function to check if the length of the username is between 3 and 25 characters. The showError() and showSuccess() functions to show the error and success indicator.
Checks whether a username is valid.
The code you have looks fine, aside from the inconsistent variable reference (see the comment by Josh Purvis).
The following regex is fine for your first name spec:
var nameRegex = /^[a-zA-Z\-]+$/;
Adding digits for your username check is straightforward:
var usernameRegex = /^[a-zA-Z0-9]+$/;
Note: There are many ways to write regular expressions. I've chosen to provide a version that matches what you started with. I encourage you to work through this Regular Expression Tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With