I have this reg ex for alphanumeric validation that I got from this post but it is not working with this function (I have a similar function for email and it works)
function checkName(field) {
var x = document.getElementById(field).value;
var y = /^[a-z0-9]+$/i;
//var z = /^[0-9]*$/;
if (x == "" || !x.match(y) ) {
alert("Invalid character");
if (x.length <= 2 || x.length >= 15) {
alert("Insert a name between 3 and 15 characters");
}
return false;
}
}
If I write some string/name I get both alerts. Can someone tell me what is wrong with this function?
Below is the approach for alphanumeric validation:
function checkName(field) { var x = document.getElementById(field).value; if (x.length <= 2 || x.length >= 15) { alert("Insert a name between 3 and 15 characters"); return false; } var y = /^[0-9a-zA-Z]+$/; if (x == "" || !x.match(y) ) { alert("Invalid character"); return false; } alert("ALL OK"); return true; }
<input type="text" id="textName" /> <button onClick="checkName('textName');">Check</button>
The Regex check for capital and small alphabets and numbers, and also checks for the length.
Your code works for me
function checkName(field) {
console.log(field);
var x = field;
var y = /^[a-z0-9]+$/i;
if (x == "" || !x.match(y) ) {
console.log("Invalid character");
}
if (x.length <= 2 || x.length >= 15) {
console.log("Insert a name between 3 and 15 characters");
}
}
//valid
checkName('testdskfjskdlf');
//invalid
checkName('slkjf*%');
//too long
checkName('jjjjjjjjjjjjjjjjjjjjjjjjjjj');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.