Reputation: 1331
I am building a validation for testing to make sure that a correct part number has been entered. Each part begins with MR in CAPS followed by a [SPACE] followed three numbers. e.g. ( MR 123 )
The problem is if i can not seem to figure out how to validate this using jquery.
The part number always begins with MR.
var type = $("input#type").val();
// Check a that a tank type has been entered.
if( type.length < 5 && type.not().contain("MR")){
$("#error_upload").html("Please enter the tank number in a format MR XXX.");
$("#type").css({borderColor:'red'}).focus();
$("name,#file").css({borderColor:'#ccc'});
return false;
}
Any help would be great.
Upvotes: 0
Views: 895
Reputation: 2265
There are several routes you could go here.
One continue by writing your validation in this manner
You would want your code to probably look something like the following
var type = $("input#type").val();
// Check a that a tank type has been entered.
if(!/^MR \d{3}$/.test(type)){
$("#error_upload").html("Please enter the tank number in a format MR XXX.");
$("#type").css({borderColor:'red'}).focus();
$("name,#file").css({borderColor:'#ccc'});
return false;
}
Integrate something like the above into jQuery Validate, since I'm assuming you'll need validation elsewhere
Simplify the entry by allowing only 3 digits and appending on 'MR ' + type
, since every one of these requires MR and a space, why ask the user to even enter it?
var num = $("input#type").val()
, type;
// Check a that a tank type has been entered.
if(!/^\d{3}$/.test(num)){
$("#error_upload").html("Please enter the tank number with only digits.");
$("#type").css({borderColor:'red'}).focus();
$("name,#file").css({borderColor:'#ccc'});
return false;
}
else {
type = 'MR ' + num;
}
Combine step 2 and 3, which would result on having an input like this <input type="text" class="required digits" maxlength="3" minlength="3" />
. This results in less complex data entry and not having to worry about simple validation logic. This is my favorite choice.
Use a input mask to prevent users from making any mistakes to begin with, but it is the most "intrusive".
Upvotes: 1
Reputation: 25228
I would suggest using regex.
if (type.match(/^MR\s[0-9]{3}$/){
...
}
Basically, it looks for MR, then a space (\s
), then 3 numbers ([0-9]{3}
). If anything else shows up, it will return false.
Upvotes: 1
Reputation: 45599
if (/^MR \d{3}$/.test(subject)) {
// Correct tank number format
} else {
// Incorrect tank number format
}
This will ensure that the entered value is always only MR
+ [SPACE]
+ 3 digits
and only that.
Upvotes: 1