Peter
Peter

Reputation: 181

JavaScript - how to validate field to allow certain character and certain length

I need to validate a textbox, so it's value consist of 10 characters (not more, not less). The below code does it, allowing me to set the restricted length for each field separately.

 function charLength(elem, min, max){
 var uInput = elem.value;
 if(uInput.length >= min && uInput.length <= max){
                alert("Invalid number of characters");
  elem.focus();
  return false;
 }else{
  return true;
 }
}

and this is how I'm calling it:

onBlur="charLength(document.getElementById('tf1'),1,9)"

but the field that I validate must not only be 10 characters long, but it also has to start with letter Z.

How would I do such validation? is it possible in the first place?

Upvotes: 1

Views: 3173

Answers (4)

Mud
Mud

Reputation: 29021

function charZ10(elem) {
    var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
    if (!pass) {
        alert("Try again, noob.");
        elem.focus();
    }
    return pass;
}

Upvotes: 1

Pradeep Singh
Pradeep Singh

Reputation: 3634

Must be

 if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")

Upvotes: 0

Egy Mohammad Erdin
Egy Mohammad Erdin

Reputation: 3413

try it also:

 function charZ10(elem, min, max){
 var uInput = elem.value;
     if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
          alert("Material number has to consist of 10 characters begining with Z");
          elem.focus();
        return false;
     }
     else return true; //i 
}

and try to add maxlength in the textbox

<input type="text" maxlength="10">

Upvotes: 2

Shadow Wizzard
Shadow Wizzard

Reputation: 66398

function charZ10(elem, min, max){
    var uInput = elem.value;
    if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
        return true;
    alert("Material number has to consist of 10 characters begining with Z");
    elem.focus();
    return false;
}

Upvotes: 1

Related Questions