How to check if the text is missing a certain character? - javascript

The task that I'm working on has an div where you need to input your email. It's a simple task, it only needs to check if the email is missing # and a period, and then display certain text, nothing too complicated. But, I've tried using the includes() function and the Chrome Console thing displays an error saying that varname.includes() it's not a function.
Here's part of my HTML code where the JavaScript should take place after using onlick:
<div class="warning"> </div>
<div class="email">
<input class="mail" type="email" name="mail" placeholder="your email">
<input class="send" type="submit" name="send" value="SEND" onclick="checkEmail()">
</div>
Bascially, what the JavaScript code needs to do is:
If it's missing #, write "missing #" in the warning div.
If it's missing ., write "missing ." in the warning div.
If it's missing both # and ., write "Your email address is not correct!" in the warning div.
If the email meets both criteria, it makes an alert saying "You are in!"
As I mentioned, I tried using includes() within an if, which didn't work, and I have no clue what else would work here. I know basics like how to make an alert or write text, I just don't know how to make the code check if the characters are there or missing. Any help on this would be greatly appreciated!

const toCheckFor = ["#", "."] // Array of all characters to check for
const text = "whatever you want" // text you want to check in
let flag = true // flipped to false if one character in the array not found
toCheckFor.forEach(e => {
flag &= text.includes(e)
})
Flag will be true if the text contains all characters in toCheckFor.

Here is an example based on your post ...
const mail = document.querySelector('input[name="mail"]'); // cache for later use
const warning = document.querySelector('.warning'); // cache for later use
function checkEmail() {
const error = {};
const text = mail.value;
if (!text.includes('#') && !text.includes('.')) {
warning.textContent = 'Your email address is not correct!';
return; // end here
}
/*
this is a shorthand
you can also write
if (!text.includes('#')) {
error.push('missing #');
}
*/
!text.includes('#') && error.push('missing #');
!text.includes('.') && error.push('missing .');
if (!error[0]) { // there are some errors
warning.textContent = error.join(' & ');
}
else { // no error
warning.textContent = "You are in!";
}
}

I suggest you'd better use regex check against the input email address by the following function:
function validateEmail(email) {
const 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(String(email).toLowerCase());
}

Related

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")]

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

Replace a part of text in textbox while typing text in it

The format of text in the text box is like this:
login -u username -p password
While typing this text I want to replace 'password' with number of '*' equal to its length. So if I type:
'login -u abc#abc.com -p abc' in text box it should display like this:
login -u abc#abc.com -p ***
And also I need to store the actual password which is being replaced.
Is there a possible way? Thank you in advance
You should parse the input value using regular expression, i.e.
<input type="text" id="inputText" />
<input type="hidden" id="actualPassword" /> <!-- Another element to store actual password -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// Function to repeat string n times */
var StringUtilities = {
repeat: function(str, times) {
return (new Array(times + 1)).join(str);
}
};
$(function(){
$('#inputText').keyup(function(){
var test = /(login[\s]+\-u[\s]+[a-zA-Z0-9#\.\s]+\-p[\s]+)(.*)/i.exec( $(this).val() ); //'login -u user123 -p password123'
if(test !== null)
{
if( $('#actualPassword').val().length < $.trim(test[2]).length )
$('#actualPassword').val( $('#actualPassword').val() + test[2].slice(-1) );
else
$('#actualPassword').val($('#actualPassword').val().slice(0, test[2].length));
$(this).val( test[1] + StringUtilities.repeat( '*', test[2].length) );
}
});
});
</script>
JS FIDDLE: http://jsfiddle.net/nmx04h1o/3/
You can use multiple text boxes and still make it look like one, command prompt. Using CSS you remove left, right borders and join them close enough. On keypress event of each textbox, check if the user typed space and change the focus to next textbox. This solution works provided you have some fixed format of input to be taken.
The way you need to look at your requirement needs to be change. Why you need to get data from user with nly one input?
You need to collect username and password differently and then you can merge the same on form submit.
$("#submit").click(function(){
$output = "login -u " + $("#username").val() + " -p " + $("#password").val();
alert($output);
return false;
});
http://jsfiddle.net/kiranvarthi/j8gL9mvx/1/
Do not do it. You can see what i've tried at the bottom of my answer.
I played around with this problem a littlebit, but when i did a facing myself another problems.
There are 2 method to do this. 1st is, when a user enter a character, you need to use the keyup function.
So, you can write a regular expression, what is catching the -p andsomecharactersherewhileitsnotspace.
Ok, the first method is to catch the last character of users password, and contcat it to a hidden field. Me and Apul Gupta tried this.
For some reason, both of our code is mess up the password, because for some reason, what i do not know, there will be * characters if you are typing to fast. I tried to replace those * characters, but in this case, some characters are lost from the password.
The other way is to get the character from keyup event. This is bad, because String.fromCharCode is returning always uppercase characters, since, keyup do not know, is there a SHIFT or CAPS LOCK happens. Maybe now you think, you can handle it, but you can not. SHIFT is simple, but you don't know, was the CAPS LOCK was turned on befor or not.
A solution could be for this, if you allow users only lowercase or only uppercase passwords, but this is bad because weekening the password.
So, think a littlebit more. Let's say, somehow we can use one of the solution. Then this whole things turn to a very complex thing, what are too expensive i think. Because, you should handle, what happens, if a user just SHIFT, LEFT ARROW, DELETE the password. You need to check, what selected with that combination of keyperss, where was the cursor, etc...
I suggest you to forget this, or try to find another way to do it.
Kiran Varthis answer is the best option i think.
What i've tried:
<input type="text" name="userInput" id="userInput" value="" />
<input type="hidden" value="" name="hiddenPassword" id="hiddenPassword" />
<script type="text/javascript">
$(function() {
String.prototype.repeat = function(num) {
return new Array(num + 1).join(this);
}
//46 = delete key
$("#userInput").keyup(function(e) {
var match = $("#userInput").val().match(/-p([\s]+)(.+)/i);
if (e.keyCode === 8) {
var deleted = $('#hiddenPassword').val().substring(0, $('#hiddenPassword').val().length - 1);
$('#hiddenPassword').val(deleted);
} else {
if (match !== null && match[2] && String.fromCharCode(e.keyCode).match(/[a-zA-Z0-9]/)) {
//Alphanumeric
$('#hiddenPassword').val($('#hiddenPassword').val() + $("#userInput").val().substring($("#userInput").val().length - 1));
$("#userInput").val(($("#userInput").val().replace(/-p (.+)/, "-p " + "*".repeat(match[2].length))));
}
}
if (match !== null && match[2]) {
console.log("Password is: " + $('#hiddenPassword').val());
}
});
});
</script>

Javascript: Field validation

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.

Categories

Resources