Javascript: Field validation - javascript

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.

Related

How to prevent transfer of values once there are some errors in the xslt file using javascript?

This is my onsubmit function where i have problem. Hope you guys will help.
function editme() {
var peru=document.editform.user_nam.value;
var mailu=document.editform.user_mai.value;
if (peru==null || peru==""){
alert("Name can't be blank");
return false;
}
if(!/(?=.{0,20}$)\S+\s\S+/.test(peru)){
document.getElementById("eredit").innerHTML="1.Value entered in the Name field is invalid;"
}
if(!/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(mailu)){
document.getElementById("erredit").innerHTML="2.Value entered in the E-mail field is invalid";
}
var aa=document.getElementById("ename").value;
var bb=document.getElementById("email").value;
var cc=document.getElementById("sele").value;
var tab=document.getElementById("myTable");
tab.rows[ind].cells[1].innerHTML=aa;
tab.rows[ind].cells[2].innerHTML=bb;
tab.rows[ind].cells[3].innerHTML=cc;
}
Here, even if there are any validation messages, my values are getting submitted to a table.I want to stop the function where there are error messages. How to do that?
Have you tried adding return false, in to the both ifs? Like this:
if(!/(?=.{0,20}$)\S+\s\S+/.test(peru)){
document.getElementById("eredit").innerHTML="1.Value entered in the Name field is invalid;"
return false;
}
if(!/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(mailu)){
document.getElementById("erredit").innerHTML="2.Value entered in the E-mail field is invalid";
return false;
}
Also would be much helpful if you can post your whole code, so I can replicate the problem to see and work with it.

How to detect if a specific string (email domain) is entered into an input to add/remove attribute/class from a button

So I know how to do the remove/add class/attribute from a submit button, but I need to be able to apply this to a button based off of entry into an input.
The scenario is this, user enters their email address, but if it's at a specific domain, ex: xxxx#troopers.gov I then want to be able to apply/remove the class, and attribute from the submit button, since this is a domain they are not supposed to enter for a registration.
I have done some similar validation in the past, and tried a few different methods in jQuery .val(), indexOf, etc. But still can't seem to get it working.
I tried something like
var badDomain = 'troopers.gov';
and then
if (!$('#input').val() === badDomain) {
doStuff();
}
but it didn't seem to get me anywhere.
I thought I may be able to do this without using a RegEx (I don't have much experience with that)
Would be nice to be able to account for case as well... and I don't mind if the solution is jQuery, or pure JS... for learning purposes, it would be great to see how I could do it both ways...
So this does what you want, by turning anything typed into the field in lower case and then comparing against a given array of bad strings. Any time the input field blurs, it checks and turns the submit on or off.
Take a look in the code to see some bad addresses for sample use.
var badDomains = [
"troppers.com",
"fooBarBaz.org",
"myReallyUselessDomainName.com",
"a.net"
]
$(function(){
$("#email").on("blur", function(){
var addressBad = false;
var thisEmail = $(this).val().toLowerCase();
for (var i=0; i<badDomains.length; i++){
if (thisEmail.includes(badDomains[i])){
addressBad = true;
}
}
if (addressBad) {
console.log("bad address!")
$(".disabledButton").attr('disabled', "disabled");
} else {
console.log("not a bad address!");
$(".disabledButton").removeAttr("disabled");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<input class="disabledButton" type="submit" disabled />
</form>
simple workaround :
var email = document.getElementById('email');
var checkEmail = document.getElementById('checkEmail');
checkEmail.onclick = function() {
if ((email.value).includes('#troopers.gov')) alert('This email address cannot be used!');
}
<input id="email">
<button id="checkEmail">Check Email</button>
there are multiple ways around though.
You can use a regex for this purpose.
HTML:
<input type="text" id="InputTest" />
<button id="TestBtn" type="button">
Validate
</button>
<p>
Valid
</p>
CSS:
.valid{
background-color:green;
}
.invalid{
background-color: red;
}
JS:
$("#TestBtn").on("click",function() {
var pattern = /\S+#troopers\.com/gi;
var str = $("#InputTest").val();
var arr = str.match(pattern);
alert(arr); // just to see the value
if(arr !== null){
$("p").addClass("invalid");
}
else{
$("p").addClass("valid");
}
});
Here is a JSFiddle. Basically, if what the user typed in the textbox matches the expression.. then the background color turns red, but if it doesn't match, then the background color turns green.
Let me know if this helps.
You can use the following Regex for the Email property of the related Model in order to accept mails having 'abc.com' suffix:
[RegularExpression("^[a-zA-Z0-9_#./#&+-]+(\\.[a-zA-Z0-9_#./#&+-]+)*#abc.com$",
ErrorMessage = "Please enter an email with 'abc.com' suffix")]

Why is my validation method for zip codes not working correctly

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");
}
}

Allow only roman characters in text fields

I am finding a way to make all the text boxes in the website only accept roman characters. Is there any easy way to do it globally.
Thanks in advance.
In modern browsers <input> accepts an attribute called pattern. This allows to restrict the valid characters in a given field.
input:invalid {
background-color:red;
}
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
For all other browsers you can find all form field via jQuery, check if a pattern-attribute exists, and check it against the value of a given field. You may also replace disallowed characters:
$('form').on('keyup blur','input',function() {
if ($(this).val() && $(this).attr('pattern')) {
//var pattern = new RegExp('^'+$(this).attr('pattern')+'$', 'g');
//$(this).toggleClass('invalid', pattern.match(!$(this).val()));
var pattern = new RegExp($(this).attr('pattern').replace(/\[/,'[^'), 'g');
$(this).val($(this).val().replace(pattern,''));
}
});
input:invalid {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
Oh, you still want to validate form inputs on the server-side. All HTML- or Javascript-stuff does not prevent all visitors of your site to submit broken stuff.
I will refer to the marked answer for the following question for the regex which filters out non-roman characters:
How to detect non-roman characters in JS?
Spoiler: the regex is /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g
Now all you need is a little bit of tinkering with jQuery:
var myInputId = "#foo"; // Or whatever you wish to use.
var input = $(myInputId);
var exp = /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g;
input.blur(function() {
input.value = input.value.replace(exp, "");
});
Include this snippet into your master page for example:
<script>
$(function(){
$('input[type=text],textarea').keypress(function(e){
var char = String.fromCharCode(e.which || e.charCode);
var rgx = /[\u0000-\u007F]/;
if (rgx.test(char) == false)
return false;
})
})
</script>
Here is my idea based on #fboes answer.
I also needed to show user whats wrong, so there is error message showing but with no redundancy when typing couple of forbidden characters in a row.
//I wanted first to assign pattern attr to every input in form but when it's happening, all "\" chars are removed from regex therefore - it doesn't work, so I had to add it in templates for every input.
let isIncorrect = false;
scope.checkPattern = function(e) {
// I don't want to allow Chineese, cyrylic chars but some other special - yes
var pattern = new RegExp('[a-zA-Z\s\.\-_äÄöÖüÜßąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+', "g");
if ($(e).is(':valid')){
return true
} else {
$(e).val($(e).val().replace(pattern,''));
return false
}
};
scope.removeAlert = function (e){
$(e).parent().find('.text-danger').remove();
isIncorrect = false;
}
// unallowed characters in order inputs
$('.my-form').on('keyup blur','input',function(e) {
if (!scope.checkPattern($(this))) {
if (!isIncorrect){
// show this error message but only once (!) and for specified period of time
$(this).parent().append('<p class="text-danger">Only latin characters allowed</p>');
isIncorrect = true;
}
setTimeout(scope.removeAlert, 3000, $(this));
}
});

validating specific email address in form with javascript

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!');
}

Categories

Resources