I have already checked previous answers on the SO. I know they are cool.
Here is my chance:
I am taking values of textbox and passing it to function to validate. It passes url correctly but not doing validations. Can someone check where is the bug? I could not identify
<html>
<head>
<title>ThenWat</title>
<script>#Vicky: above regex does not filter:
function validateURL($URL) {
alert($URL);
$pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
$pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
alert("correct");
return true;
} else{
alert("Incorrect");
return false;
}
}
</script>
</head>
<body style="height: 560px">
<form>
<label>Enter URL: <input type="text" value="http://www.paulgraham.com/herd.html" name="sent" id="t1" style="width: 400px; height:40px;" ></label><br/>
<div style="z-index: 1; left: 420px; top: 160px; position: absolute; margin-top: 0px"> <button onclick="validateURL(document.getElementById('t1').value)";> Fire me </button>
</div>
</form>
</body>
</html>
UPDATE
<html>
<head>
<title>ThenWat</title>
<script>#Vicky: above regex does not filter:
function validateURL($URL) {
var str=$URL;;
var n=str.match(/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g);
document.getElementById("demo").innerHTML=n;
//alert("correct or incorrect as per validation"); how to do this?
}
</script>
</head>
<body style="height: 560px">
<form>
<label>Enter URL: <input type="text" value="http://www.paulgraham.com/herd.html" name="sent" id="t1" style="width: 400px; height:40px;" ></label><br/>
<div style="z-index: 1; left: 420px; top: 160px; position: absolute; margin-top: 0px"> <button onclick="validateURL(document.getElementById('t1').value)";> Fire me </button>
</div>
</form>
</body>
</html>
You can use $pattern1.test($URL) or $pattern1.match($URL)instead of using preg_match($pattern_1, $URL)
Try this:
function validateURL($URL) {
alert($URL);
$pattern_1 = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
$pattern_2 = /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
if($pattern_1.test($URL) || $pattern_2.test($URL)){
alert("correct");
return true;
} else{
alert("Incorrect");
return false;
}
}
var str="The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g);
To match string with regular expression in javascript you need to use match(). Check http://www.w3schools.com/jsref/jsref_match.asp
regexp for URL : /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
Update:
function myFunction(){
var str="http://www.google.com";
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
if(str.match(regexp)){
alert("okay");
}else{
alert("not okay");
}
}
regular expression library : https://github.com/javaquery/regexp/blob/master/regexp-0.0.1.js
The problem for your is your regular expression
i have a pretty good one i normally use like this:
[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?
It checks first if something before the first . (ex. testing in testing.mywebsite.com) then checks mywebsite and last after the last dot it even checks the ending
Related
I need help sorting this out. Everything seems to work fine until it gets to receive the results of request, where someting goes wrong. The idea of the project is a Web App, where user gets 2 fields for name and date of birth. After filling them the information is verified by checking in the spreadsheet with relevant information. If everything is okay, the program next obtains appropriate id with getSheetId(), generates <iframe> code for access and should be returning it with HtmlService. However, something makes it return undefined.
Code.gs
function doGet() {
Logger.log("Login is loading")
return HtmlService
.createTemplateFromFile('index')
.evaluate()
//.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function evaluate(name, date) {
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho')
.getSheetByName('key');
Logger.log(t.getSheetId());
Logger.log(name);
Logger.log(date);
var v = t.getRange("B2:D200");
var i = 0;
for (i = 1; i < 200; i++) {
if (v.getCell(i, 2).getValue() == name) {
Logger.log(v.getCell(i, 2).getValue());
Logger.log(name & " = the name");
Logger.log(new Date(v.getCell(i,3).getValue()).getTime());
var pdate = date.split(".");
Logger.log(new Date(pdate[2],pdate[1],pdate[0]).getTime());
var t = v.getCell(i,3).getValue();
Logger.log(pdate);
Logger.log(t.getFullYear());
Logger.log(t.getMonth());
Logger.log(t.getDate());
if (new Date(t.getFullYear(),t.getMonth()+1,t.getDate()).getTime() == new Date(pdate[2],pdate[1],pdate[0]).getTime()) {
Logger.log("match found");
include(v.getCell(i,1).getValue());
break;
} else {
Logger.log("Bad date");
return "<h2>Wrong Input. 404.</h2>";}
}
}
if (i >= 199) {
Logger.log("Bad name");
return "<h2>Wrong Input. 404.</h2>";
}
}
var hhtml = "";
function include(name) {
var html = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTeFjXOSsBRAKjbFLUSBGZOXtmjZO_4RtxxrQtXbk9sxZkF5Kdjs9OIs0tSQwekjYbOTn7JJ-_iCdeD/pubhtml?gid='
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho').getSheetByName(name);
if (t == null) {
Logger.log("Page not found");
return "<h1>Wrong Input. 404.</h1>"
} else {
html += t.getSheetId();
}
Logger.log(name);
html += '&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
html += '<br><br><br><h3>Рейтинг групи</h3><iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRF1MobEoKdxvO_SopGTvl-WzqEQ3nQXd6Jo_a7RTAg09yluO32AClwd4krWnVHXGQllPPwOsDeYYzN/pubhtml?gid=2096708929&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
Logger.log(html);
hhtml = HtmlService.createHtmlOutput(html).getContent();
return HtmlService.createHtmlOutput(html).getContent();
}
function getHtmlCode() {
return hhtml;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="mainForm">
<h2> Будь-ласка введіть своє прізвище українською мовою та дату народження у форматі день.місяць.рік (наприклад: 22.06.2018) </h2>
<form>
<div>
<div class="inline form-group">
<label for="name">Прізвище</label>
<input type="text" id="nameInput" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Дата Народження</label>
<input type="text" id="dateInput" style="width: 150px;">
</div>
</div>
<button class="action" type="button" id="submitButton">Submit</button>
</form>
</div>
<style>
.hidden {
display:none;
}
.form-group {
margin: 2px 0px;
}
#submitButton {
margin: 4px 0px;
}
body {
margin-left: 50px;
}
</style>
<script>
$(function(){
console.log('startup')
$('#submitButton').on('click', function(){
console.log("data get");
function respondent(value)
{
$('#mainForm').toggleClass('hidden');
console.log("script is success");
console.log(value);
document.getElementById('Response').innerHTML = value
}
google.script.run.withSuccessHandler(respondent).evaluate(document.getElementById('nameInput').value, document.getElementById('dateInput').value);
})
})
</script>
<div id="Response">
<h2>Waiting for data...</h2>
</div>
</body>
</html>
After cleaning up your code formatting, it looks like you're only returning a value from evaluate() during the Wrong Input error conditions. Nothing is returned otherwise.
Perhaps you meant to add a line like this at the end of evaluate():
return include(name);
Also, the hhtml global variable and getHtmlCode() functions aren't useful in the context of Apps Script. Each execution is in a separate instance with no state being carried over. Which mean getHtmlCode() will always return an empty string.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function light() {
if (document.getElementById("push").value == "OFF") {
document.getElementById("bulb").style.backgroundImage = url("1.png");
document.getElementByID("push").value = "ON";
}
else {
document.getElementById("bulb").style.backgroundImage = url("2.png");
document.getElementByID("push").value = "OFF";
}
}
</script>
<center>
<input type="button" id="push" onclick="light()" value="OFF" />
<div id="bulb" style="background-image:url(2.png);width:320px;height:420px">
</div>enter code here
</center>
</body>
</html>
This line:
document.getElementById("bulb").style.backgroundImage = url("1.png");
attempts to call a function called url and pass a string to it, and then assign the result of that to the backgroundImage property.
Instead, you want to assign a string to backgroundImage directly:
document.getElementById("bulb").style.backgroundImage = "url(1.png)";
// Note ------------------------------------------------^----^----^^
Example:
document.getElementById("bulb").style.backgroundImage = "url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32)";
<div id="bulb" style="width: 32px; height: 32px"></div>
That said, it would be better to define your styling and such in CSS and then associate those styles with elements using selectors, for instance via a class association:
CSS:
.class-saying-what-the-image-represents {
background-image: url(1.png);
}
JavaScript:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
Example:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
.class-saying-what-the-image-represents {
background-image: url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32);
}
<div id="bulb" style="width: 32px; height: 32px"></div>
i m new to angular programming.
so i was given a task to create an app in angular to check the strength of password based on input string length.
the following is my code , please check it.
<!DOCTYPE html>
<html>
<head>
<title>password strength</title>
<style type="text/css">
.red{
background-color: red;
}
.orange{
background-color: orange;
}
.green{
background-color: green;
}
</style>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript">
var ans= angular.module("myapp",[]);
ans.controller("pswdstr",function($scope){
$scope.show=function(){
var pswdlen= $scope.pswd.length;
if (pswdlen==0)
{
$scope.color="";
$scope.validation="Enter password";
}
else if (pswdlen<=5)
{
$scope.color="red";
$scope.validation="password is weak";
}
else if (pswdlen>5 && pswdlen<=8)
{
$scope.color="orange";
$scope.validation="password is ok";
}
else if (pswdlen>8)
{
$scope.color="green";
$scope.validation="password is strong";
};
};
});
</script>
</head>
<body ng-app="myapp" ng-controller="pswdstr">
<label for="pswd">Enter password</label>
<input type="password" name="pswd" id="pswd" ng-model="pswd" ng-keypress="show()"></input>
<div class='{{ color }}' ng-if="pswd">
{{ validation }}
</div>
</body>
</html>
the problem i am facing is that the app is not working.
when the string length is below 5 or below 8 according to the condition the div color should change to red along with its validation. but its not working that way.. please help.
and guys please post the detailed answer as i am a beginner in this scripting.
thank you.
I think that your problem be define nd-model as ng-model.
i put your sample here and work corrctly.
use ng-change insted of ng-keypress. now it work correctly.
var ans= angular.module("myapp",[]);
ans.controller("pswdstr",function($scope){
$scope.show=function(){
var pswdlen= $scope.pswd.length;
if (pswdlen==0)
{
$scope.color="";
$scope.validation="Enter password";
}
else if (pswdlen<=5)
{
$scope.color="red";
$scope.validation="password is weak";
}
else if (pswdlen>5 && pswdlen<=8)
{
$scope.color="orange";
$scope.validation="password is ok";
}
else if (pswdlen>8)
{
$scope.color="green";
$scope.validation="password is strong";
};
};
});
.red{
background-color: red;
}
.orange{
background-color: orange;
}
.green{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="pswdstr">
<label for="pswd">Enter password</label>
<input type="password" name="pswd" id="pswd" ng-model="pswd" ng-change="show()">
<div class='{{ color }}' ng-if="pswd">
{{ validation }}
</div>
</div>
You can use ng-change instead of ng-keypress inside input
see here working code
use keydown instread of keypress and instread of
$scope.pswd.length
use
$scope.pswd.length+1
and alert in your check to see its working or not
I am working on registration form for my project in AngularJs. Users can register with his/her Email/Phone. I need to validate that particular text-box.
I have validations for both, with different text fields, with ng-pattern. But how can I validate for both in one text field?
I have updated my code, here:- enter code here
http://plnkr.co/edit/mCVxHxl2DIvqOYtVapRN?p=preview
Use /^([_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|(\d+$)$/
Demo
You can use a pipe '|' to OR two regular expressions together:
/<email-pattern>|<phone-pattern>/
so your final regex would be:
/^([_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|\d+$/
You can use angular form validation and ng-pattern directive for input use ng-pattern="/^(?:\d{10}|\w+#\w+\.\w{2,3})$/"
Working Demo
var app = angular.module("MY_APP", []);
app.controller("MyCtrl", function($scope) {
$scope.submitted = false;
$scope.submit = function(userData){
console.log(userData)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MY_APP">
<div ng-controller="MyCtrl">
<form name="userForm" novalidate ng-submit="userForm.$valid && submit(userData)">
<div class="errorMsg" ng-show="submitted==true && userForm.$invalid">
<ul>
<li ng-show="submitted==true && userForm.emailphone.$error" class="errorMsg">
wrong format, It should be email or 10 digit mobile number
</li>
</ul>
</div>
<input type="text" name="emailphone" ng-model="userData.user" id="emailphone" required
ng-pattern="/^(?:\d{10}|\w+#\w+\.\w{2,3})$/" />
<button type="submit" ng-click="submitted = true">Submit</button>
</form>
</div>
</div>
guys here is the Regex for email or phone number Please have look I hope it's helpful.
Thanks
^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$
Here is an example as well.
https://jsfiddle.net/sanat/b2m436L5/17/
function validate(){
var value = $("#email_phone").val();
var regex = new RegExp('^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|(^[0-9]{10})+$');
if(value){
if(!regex.test(value)){
$("#error").text("Please enter valid email address or phone number.")
}else{
$("#error").text('')
}
}else{
$("#error").text('This field is required.')
}
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
#error{
font-size:14px;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<div>
<input type="text" placeholder="Email/phone" id="email_phone">
<button onClick="validate()">Submit</button>
</div>
<span id="error"></span>
</div>
This code might work for you: Here is the ans of your question
<script type="text/javascript">
function validate(){
var phoneNo = document.getElementById('txtEmailormob');
var c=document.forms["myForm"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
var errorMsg = document.getElementById("errorMsg");
var successMsg = document.getElementById("successMsg");
if(phoneNo.value==""||phoneNo.value==null){
errorMsg.style.display="block";
document.getElementById("errorMsg").innerHTML = "Please enter your Mobile No or Email ";
return false;
}
if ((phoneNo.value.length < 10 || phoneNo.value.length > 10) && (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)) {
errorMsg.style.display = "block";
successMsg.style.display = "none";
document.getElementById("errorMsg").innerHTML = " Mobile No. is not valid, Please Enter 10 Digit Mobile No or Please Enter valid Email. ";
return false;
}
successMsg.style.display = "block";
document.getElementById("successMsg").innerHTML = " Success ";
errorMsg.style.display = "none";
return true;
}
</script>
Simple code
Complete Working Like Validate : amazon, Facebook, uber.etc Email or Phone Number Using Single Input...
Try this its working ..............
<script>
$(document).ready(function () {
$("#cuntryCode").hide();
$("#useridInput").on('input', function () {
var len = $("#useridInput").val().length;
if (len >= 2) {
var VAL = this.value;
var intRegex = /^[1-9][0-9]*([.][0-9]{2}|)$/;
if (!intRegex.test(VAL)) {
$('#error-caption').html('Invalid email. Please check spelling.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").hide();
} else {
if(len < 10){
$('#error-caption').html('Invalid mobile number. Please try again.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").show();
}else{
$('#error-caption').html('Invalid mobile number. length must be 10 digit.');
$('#error-caption').css('color', 'red');
}
}
}else{
$("#cuntryCode").hide();
$('#error-caption').html('');
}
});
});
</script>
<form class="push--top-small forward" method="POST" data-reactid="15">
<h4 id="input-title" data-reactid="16">Welcome back
</h4>
<label class="label" id="input-label" for="useridInput" data-reactid="17">Sign in with your email address or mobile number.
</label>
<div style="margin-bottom:24px;" data-reactid="18">
<div >
<div id="cuntryCode" class="_style_4kEO6r" style="float: left; height: 44px; line-height: 44px;">
<div tabindex="0" > +241
</div>
</div>
<div style="display:flex;">
<input id="useridInput" autocorrect="off" autocapitalize="off" name="textInputValue" class="text-input" placeholder="Email or mobile number" aria-required="true" aria-invalid="false" aria-describedby="error-caption input-title">
</div>
</div>
<div id="error-caption">
</div>
</div>
<button class="btn btn--arrow btn--full" data-reactid="24">
<span class="push-small--right" data-reactid="25">Next
</span>
</button>
</form>
Here is my HTML code:
<p style="align-content: center">
<A style="align-content: center" HREF="newpopup.html" onClick="return popup(this, 'stevie')">my popup</A><br>
</p>
<p align="center">
<input type="button" onclick="popup(this, 'about') " value="CLICK HERE">
</p>
And JavaScript:
function popup(mylink, windowname)
{
if (! window.focus)
return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=400,height=200,scrollbars=yes');
return false;
}
My button 'CLICK HERE' pops-up a window but it is empty. I want my button to work just like above URL link 'my popup'.
So I want to open the contents of newpopup.html in my pop-up window on a button click.
My URL link for pop-up is working fine, I want the button to work thesame.
mylink (the button's this) isn't a string, so you try to open mylink.href:
if (typeof(mylink) == 'string')
href = mylink;
else
href = mylink.href;
But buttons don't have href properties, so it's as if you wrote:
window.open(undefined, 'about', 'width=400,height=200,scrollbars=yes');
which opens a blank page, as expected. If you want to open the same page as the link, use:
onclick="popup('newpopup.html', 'about');"
Try this simple piece of code:
<script>
function fullwindowpopup(){
window.open("newpopup.html","bfs","fullscreen,scrollbars")
}
</script>
<center>
<form>
<input type="button" onClick="fullwindowpopup()" value="CLICK HERE">
</form>
</center>
Pop ups can be tricky if you want them to "float" above your html page. This can be obtained by using an absolute placement to place a "filter" and the required frame over your current page. Usually I go for something like this:
HTML
<body>
...
<div class='myPopup'>
<iframe src='http://www.myurl.com' id='popup-frame'>
</iframe> <!-- /#popup-frame -->
</div> <!-- /.myPopup -->
...
</body>
CSS:
.myPopup {
position: absolute;
width: 100%;
height: 100%;
background-color: #A8A8A8;
opacity: 0.4;
display: none;
z-index: 100;
}
#popup-frame {
position: absolute;
top: 50%;
left: 50%;
}
Stack Overflow Check this example.
The javascript is below
<script>
function openPopup() {
document.getElementById("boxPopup").style.display = "block";
}
function closePopup() {
document.getElementById("boxPopup").style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
var modal = document.getElementById('boxPopup');
if (event.target == modal) {
closePopup();
}
}
</script>