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>
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.
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!");
}
});
});
JSFiddle
If you have any questions about the regex, ask away!
Related
I have a form that uses asp:requiredvalidator and some custom javascript to apply a red 1px border around any field that hasn't been correctly filled in.
This works perfectly, but now I want to be able to immediately remove the red border when the user correctly fills in the field.
To achieve this, I am using Jquery's focusout() method to compare the user input to a regular expression. So far I have this correctly working on every field (including email validation) except zip code. For some reason, all the validation methods I have written work perfectly except for zip code.
Here is a working email validation for example
if (id == "email1" || id == "email2") {
emailValue = e.target.value;
if (validateEmail(emailValue)) {
$("#" + id).removeClass("ErrorControl");
}
else {
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This works perfectly and removes the red border as soon as the field losses focus and the email is valid.
But I cannot get my zip validator working, even though it works almost the exact same way.
Here is the non working zip example
//Zip code also require special validation to confirm
if (id == "zip") {
zipValue = e.target.value;
if (validateZip(zipValue)) {
$("#" + id).removeClass("ErrorControl")
}
}
//Simple zip validator
function validateZip(zip) {
var re = /^[0-9]{5}$/;
return re.test(zip);
}
Unfortunately this still removes the red border, even when I enter just letters in it! Why is this happening?
https://jsfiddle.net/hhjvstp3/
I have given both email and zip a class of ErrorControl since I cannot run asp validators on jsfiddle. This works exactly like I am describing. Email validates well, zip code removes the border no matter what.
Updated fiddle
You can see which line removes the ErrorControl class from zip
if (id == "firstname" || id == "lastname" || id == "address1" || id == "city" || id == "amount") {
//id == "zip" shouldn't be here
if (e.target.value != "") {
$("#" + id).removeClass("ErrorControl");
}
}
I'm setting up a form and in it I've already coded verifying that there is an entry in the email form box as you can see here
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value
mailingVal = trim(mailingVal);
if(mailingVal == "" ){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
}else{
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
However I need it to also validate that it is a CERTAIN email address and not just any email address. For example it must be an #gmail.com address and not an #hotmail.com or #anythingelse.com. Any guidance would be appreciated thank you!
You can use regex:
if (mailingVal && mailingVal.match(/#gmail\.com$/i)) {
// it's gmail
}
A better approach might be to use a regex which makes sure that the string to match ends with #gmail.com
var re = /#gmail\.com$/i;
if(re.exec(mailingVal) !== null) {
// the test passed!
}
This will ensure that the string ends with #gmail.com and does not contain any extra characters after the .com
Using that regex, someone#gmail.com will match, but someone#gmail.comm will not. As will someone#Gmail.com or someone#GMAIL.COM (and so on) because of the /i switch.
If you wanted it to only match case-sensitively, just remove the /i switch, so the regex would read like
var re = /#gmail.com$/
Update
Here is the regex solution in your code, changed the exec to test (which just returns true or false, depending on whether the regex matches or not):
function checkMailing(){
//if we want to refer to the email field - which has the name 'email' - we would use the form variable (created above), as such:
//theForm.email
//you this with the name of any field iside of the form
//alert(theForm.email.value);
//use an if statement to check the value of the form
var mailingVal = theForm.mailing.value,
re = /#gmail\.com$/i;
mailingVal = trim(mailingVal);
if(!re.test(mailingVal)){
//error message
//add a dropshadow to the field (to highlight it)
theForm.mailing.style.boxShadow = "0px 0px 6px #01FFFF";
//from the form field, go up to the parent (the div with the class 'formbox', then inside of that for the div with the class 'fieldInfo', and change the text contents to be an error message
setMessage(theForm.mailing, "error", "You must enter an address");
/*theForm.email.parentNode.querySelector("div").innerHTML = "You must enter an email!";
theForm.email.parentNode.querySelector("div").className = "error";*/
} else {
//if the user entered an email (or in this anything) give them positive feedback
theForm.mailing.style.boxShadow = "";
setMessage(theForm.mailing, "correct", "Perfect");
/*theForm.email.parentNode.querySelector("div").innerHTML = "Perfect)"
theForm.email.parentNode.querySelector("div").className = "correct";*/
}
}
This should work for you. I do have one question about the trim() function you are using. What is it? Is there a library you are using, or is the trim function something you wrote? I would just use String.prototype.trim to remove whitespace from the beginning and end of the mailingVal.
If you know wich exactly mail vendor you want to check, then try this one:
if (mailingVal.length && mailingVal.indexOf('#gmail.com') > -1 ) console.log('that is gmail!');
You also may need to put your string to lover case to be sure that 'Gmail' is also valid
mailingVal = mailingVal.toLowerCase()
UPD:
as metioned in comments, this case will make mails like 'wut#gmail.commadot' also valid.
To prevent that you can try this check:
mailingVal = mailingVal.split['#'];
if (mailingVal.length > 2) {
console.log('not Valid email');
} else {
if (mailingVal[1].toLowerCase() === 'gmail.com') console.log('Bingo!');
}
so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.
I have the following validation on a form field:
$(".controlsphone input").blur(function() {
var ree = /^\d+$/;
if(ree.test(document.getElementById("register_telephone").value))
{
$(this).css('border-color','green');
$(this).siblings('.info').css('display','none');
$(this).siblings('.error').css('display','none');
$(this).siblings('.valid').css('display','inline-block');
$("#email_error401112").hide();
$('#registerErrors').hide();
}
else
{
$('#registerErrors').show();
$('#email_error401112').remove();
$('#registerErrors').append('<p id="email_error401112">Please enter a phone number</p>');
}
});
I would like to only validate the field if a number exists. The field is not required, but if there is content within the field, it needs to be valid (a number)
How does the above code look? Any ideas what i can do to implement this?
Cheers, Dan
Use
var ree = /^\d*$/;
because + stands for one or more, excluding zero.
while * stands for zero or more
i have this this code:
$(document).ready(function(){
$("input").focus(function(){
$(this).css('outline-color','#559FFF');
$(this).blur(function(){
$(this).css("outline-color","#FF0000");
});
});
$("input").click(function(){
var value = $(this).val(function(){
$(this).html("");
});
});
$(".awesome").click(function(){
var toStore = $("input[name=name]").val();
if((toStore===/[a-zA-Z]/)===true){
$("#contain").children().fadeOut(1000);
$("#contain").delay(5000).queue(function(){
$("#contain").append("<p>welcome : " + toStore + " </p>");
});
}else{
alert("You Must Put a Valid Name");
}
});
});
i want my code to test and catch the value of my input and if the value is a characters
between a-z including capitalize with a space between two words like: "FirstName LastName"
if its ok thne procced to:
$("#contain").children().fadeOut(1000);
$("#contain").delay(5000).queue(function(){
$("#contain").append("<p>welcome : " + toStore + " </p>");
});
else alert the user that he must put valid characters.
I think this regex should work:
if (/^[A-Za-z]+ [A-Za-z]+$/.test(toStore)) {
}
and should be put in place of your if((toStore===/[a-zA-Z]/)===true){
DEMO: http://jsfiddle.net/tDVWk/
This checks that the input follows this:
Starts with 1 or more alphabetic characters (any can be uppercase or lowercase)
Contains a space after the previous set of characters
Ends with 1 or more alphabetic characters (any can be uppercase or lowercase)
If you want to be more strict and require that each name start with an uppercase letter and the rest be lowercase, you can use:
if (/^[A-Z][a-z]? [A-Z][a-z]?$/.test(toStore)) {
}
But that isn't ideal, as names are very different and could easily be something like "McLovin"...where this second example would definitely fail. Hopefully my first example should complete what you need.
Of course, there's always the debate that you shouldn't restrict something like this so much. What if their name is more than just a first and last? What if they have a suffix, like "III" (or actually "3"), designating they are the third of their family with that name? What if people want to include their middle name (on purpose or accident)? It might make more sense for you to use two textboxes for each name, making it more clear for the user. That way, all you have to do is validate that each is filled in (and maybe only has alphabetic characters). Then again, I'm not sure what your requirements are and what this textbox you already have is for :)
Something like this? You'll need to add your code where you need it.
<script>
function validateInput(obj, e){
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
var AllowRegex = /^[\ba-zA-Z,\s-\f\n\r\t\v]$/;
if (AllowRegex.test(character)){
return true;
}
else{
alert('!');
return false;
}
}
</script>
<input id="input1" onkeydown=" return validateInput(this,event) "/>