Only allow Specific Domain within a Text Input Field - javascript

Ok so I've got a text input box which is for people to link there Tripadvisor page to a profile. I want it so when they paste the URL in it gets checked for the correct URL, so if: http://www.tipadvisor.com/ or if http://tripadvisor.com/ then allow link but if something like: http://www.differentdomain.com is inputed it will reject it.
Is there anything in JavaScript or jQuery that could do this?
All advice greatly appreciated.

/* author Vicky Gonsalves*/
function tValid(url) {
var p = /^(?:http?:\/\/)?(?:www\.)? (?:tripadvisor.com\/)?$/;
return (url.match(p)) ? RegExp.$1 : false;
}
this function will match if the provided string is a valid tripadvisor.com or not and will return true or false accordingly
example usage:
<input type='text' id='tripurl' />
<button type='button' onclick='validateUrl()'>validate</button>
<script>
var url=document.getElementById('tripurl').value;
if(tValid){
// url is valid
}else{
//url is invalid
}
</script>

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

Javascript - Remove query string from current url

I need to remove query string value from the url once submit button is clicked. Can i able to do this with jquery?
Current Url:
siteUrl/page.php?key=value
After Page submit:
siteUrl/page.php
Actually i have landing to current page from another one with query string. I need query string value when page loads first time to prefill some details. But once i submitted the form, i need to remove query string value.
I have tried like this.
$('#submit').click(function(){
var newUrl = window.location.href.replace(window.location.search,'');
window.location.href = newUrl;
return false;
});
It makes changes in url as expected. but cant able to get the posted values.
Thanks in advance :)
How about this one. Hope it helps :)
$('#myform').submit(function(event){
event.preventDefault();
var currentURL = window.location.href ;
location.href = currentURL.substring(0, currentURL.indexOf('?'));
});
index.html
<form id = "myform">
<input type = "text">
<input type = "submit" id = "submit" value = "Send">
</form>
function getQueryString(url) {
return url.split("?")[0];
}
var Url=getQueryString("siteUrl/page.php?key=value");
console.log(Url);
You may try this for getting url
Unfortunately i cant able to do it with javascript or jquery. So i go through with php redirection, now it works.
<?php
if(isset($_POST['Submit'])) {
// actions
if(isset($_REQUEST['key']) && ($_REQUEST['key'] != "")) {
header('Refresh: 1;url='.$_SERVER['PHP_SELF']);
}
}
?>
Thanks all :)

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

Remove http:// and www from form field while customer is typing, and show alert?

I have a form in which is a field (#domain).
Here I want the customer to add their own domain name. Often I see that they input wrong, even thought the instructions are short and clear.
To make it more user friendly, and to avoid errors - I'd like to add a validator or auto corrector.
This is a jquery and bootstrap environment.
This is the solution I have made for now:
http://jsfiddle.net/Preben/ew1qoky9/1/
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
</form>
and the javascript:
$('#domain').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This removes all special caracters and spaces on the fly. However without telling the customer.
Customers still input http:// and http://www. - and I'd like to auto-remove these too.
Can I add something in the regex or js to make this happen? - Or what is a suggested working solution?
Is there a way to show a message/ alert if the customer enters a special caracter? Like "Please use only a-z, 0-9 and dots. If your domain has special caracters, please enter the ACE-version of your domain name." - Either a bootstrap alarm, or a standard js alert?
PS: I found this: Regex for dropping http:// and www. from URLs about removing the above from urls, but I don't understand how to use this in my code. I am very thankful for suggestions. Please play with the fiddle :-)
Per your code, user cannot type special characters like :// but user can paste it. To handle such cases, you can validate it on blur event. Following is the fiddle depicting same. Also I have added a simple check for"http", and will show error if http is entered. You can configure per your requirement.
Code
(function() {
var regex = new RegExp("^[a-zA-Z0-9\-_.]+$");
$('#domain').keypress(function(e) {
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
e.preventDefault();
return false;
});
$("#domain").on("blur", function(e) {
var str = $(this).val();
if (regex.test(str)) {
if (str.indexOf("http") >= 0) {
$("#lblError").text("Domain name cannot have HTTP in it.").fadeIn();
return false;
}
$("#lblError").fadeOut();
} else {
$("#lblError").text("Please use only a-z, 0-9 and dots.").fadeIn();
return false
}
});
})()
.error {
color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input placeholder="input your domain (WITHOUT http:// and www.)" class="form-control" name="domain" type="text" autocomplete="off" id="domain" style="max-width:320px">
<p class="error" id="lblError"></p>
</form>
Here you go:
$('#domain').on('input', function() {
rawInput = $(this).val();
console.log(rawInput);
cleanInput = rawInput.replace('www.', '');
cleanInput = cleanInput.replace('http://', '');
cleanInput = cleanInput.replace('https://', '');
console.log(cleanInput);
$(this).val(cleanInput);
});
See it in action here:
https://jsbin.com/birunuyeso/edit?html,js,console,output
Look at your JavaScript console and you'll see what it's doing. In production you can obviously remove any of the lines that use console.log().

check whether any html tags entered in textarea using javascript

I'm having a simple commenting system, where i want the user should not type any html special chars, if they done like that they should give an alert of "html tags not allowed". How to do it?
while submitting, a ajax call is passed to another page to store it in db.
So in the javascript itself(before ajax call), how to find is there any html tags in the entered comment.
Any suggestion.
To check you can create an element in the DOM, inject the comment into it and use [element].getElementsByTagName('*') to check for any html element. If its length is not 0, there are html elements in the comment. Something like:
document.querySelector('#check').addEventListener('click', doCheck);
function doCheck(e) {
var chkEl = document.createElement('div'),
isok,
report,
value = document.querySelector('#testing').value;
if (!value.length) {return true;}
chkEl.innerHTML = value;
report = document.querySelector('[data-report]');
isok = !chkEl.getElementsByTagName('*').length;
report.setAttribute( 'data-report',
!isok
? 'you can\'t enter html here!'
: 'text looks ok' );
report.style.color = isok ? 'green' : 'red';
}
[data-report]:before {
content: attr(data-report);
}
<textarea id="testing" placeholder="type some stuff"></textarea>
<span data-report=""></span>
<br>
<button id="check">check for html</button>
Disclaimer: you should always check server side too.
You can use the following statement with regex:
if (/<[a-z][\s\S]*>/i.test(textareaContent)) {
alert("html tags not allowed");
}
Kooilnc is right. You should always check user input on server side as well.
Please see this question Check if a string is html or not
removing html tags in comment
function sanitizeString(str) {
str = str.replace(/[^a-z0-9áéíóúñü \.,_-]/gim, " ");
return str.trim();
}

Categories

Resources