Reputation: 69
I was trying to validate a textbox input via jquery, but I don't know how to apply certain rules for this kind of situation.
Here is the deal: I want the textbox to accept only alphanumeric inputs (A-Z and 0-9) and using ' . ' as separators for certain cases. If the textbox has a value of 16 (in this case, then the user must've typed something like this: 67EA981XXVT110TP), then I want to validate to check if there's only letters and numbers in the input, but if the value is 19 (something like: 67EA.981X.XVT1.10TP) then it has to be checked to confirm that the separators are in the right position (every 4 character input) and if there is only alphanumeric values in the field.
This is what I was trying to do (I'm using Razer Engine View)
<script type="text/javascript">
$(function () {
$('#txtCode').blur(function () {
if ($('#txtCode').val().length > 19) {
alert('Invalid field input!')
}
else if ($('#txtCode').val().length >= 1 && $('#txtCode').val().length < 16) {
alert('Invalid field input!')
}
if ($('#txtCodVerificador').val().length == 16) {
//check if there is only numbers and letters in the field
}
if ($('#txtCodVerificador').val().length == 19) {
//check if there is only numbers and letters in the field and if the separators are in the right place (every 4 character input)
}
});
});
</script>
Upvotes: 0
Views: 90
Reputation:
You have mentioned I'm using Razer Engine View so I assume this is asp.net-mvc. Your current implementation means that you need to repeat all you validation again on the server when you submit. To handle this all out of the box, add a RegularExpressionAttribute
to your property
[RegularExpression(@"^[A-Z0-9]{16}|([A-Z0-9]{4}\.){3}[a-zA-Z0-9]{4}$", ErrorMessage = "...")]
public string Code { get; set; }
and in the view
@Html.TextBoxFor(m => m.Code)
@Html.ValidationMessageFor(m => m.Code)
If your view includes jquery.validate.js
and jquery.validate.unobtrusive.js
, then you get both client and server side validation (your $('#txtCode').blur(..
script is not required)
Credit to ArcaneCraeda's answer for the regex.
Upvotes: 2
Reputation: 1275
Give this a shot:
$(function () {
$('#txtCode').blur(function () {
if ($('#txtCode').val().match(/^[A-Z0-9]{16}$/)) {
console.log("Matches the 16");
}else if ($('#txtCode').val().match(/^([A-Z0-9]{4}\.){3}[a-zA-Z0-9]{4}$/)) {
console.log("Matches the 19");
}else{
console.log("Does not match!");
}
});
});
If you have any questions about the regex, ask away!
Upvotes: 1