I would like to check if the given url is valid.
It should accept:
www.gmail.com
and should reject:
www.gmail
I tried using this /((ftp|http|https):\/\/)?(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
It works but if the given input is www.gmail it does accepts it.
Any Ideas?
UPDATE
http://jsfiddle.net/aabanaag/VktaX/
You could use Jquery Validate plugin for that.
$("#myform").validate({
rules: {
field: {
required: true,
url: true
}
}
});
You can find about it here
try this .It is working for me
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
In jQuery
you can use url validation
<input type="text" class="url"/>
solved my problem:
found this while googling over the internet.
/^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/
var pattern1 = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/;
var result = "www.gmail";
if (pattern1.test(result)) {
console.log("test");
}else{
console.log("fail");
}
It works best.
Related
I would like a reload.location click-event only if a checkbox is checked. To me this seems to be basic conditions, but it's not working. Perhaps a different approach is needed? What I figured out, is when the checkbox is ticked, there is no html change in the <input type="checkbox"> element. Maybe this is the reason or is the combination of these conditions not possible? The else statement is a call back to the previous UI page. In below attempt, it's skipping the if-statement.
My attempt:
$(document.body).on("click", "#button", function(){
if (document.getElementById('checkbox').checked) {
location.reload(true);
} else {
return_to_page( this.dataset.return )
}
});
Above is working, however it's ignored due to the missing preventDefault:
$(document.body).on("click", "#button", function(e){
e.preventDefault();
//etc
});
checked is not a property of a jQuery object. You can use prop() to get the property instead:
$('#button').click( function() {
if ($('#checkbox').prop('checked')) {
location.reload(true);
}
// alternative #1 - use the 'checked' property of the Element in the jQuery object:
if ($('#checkbox')[0].checked) {
location.reload(true);
}
// alternative #2 - use the 'checked' property of the Element outside of jQuery:
if (document.getElementById('checkbox').checked) {
location.reload(true);
}
});
Here's a working example:
$('#button').click(function() {
if ($('#checkbox').prop('checked')) {
// location.reload(true);
console.log('Reload would happen now...');
} else {
console.log('Staying on the current page');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" id="checkbox" />
Reload?
</label>
<button id="button">Go</button>
$('#button').click( function() {
if( $("input[id='checkbox']:checked") ) {
location.reload(true);
}
});
alternative
$('#button').click( function() {
if( $('#checkbox').is(':checked') ) {
location.reload(true);
}
});
All in a one plate methods:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked
I'm working with Dojo-1.9.1 and trying to build a templatized form for our application. I'm using noty to display an error alert when form validation fails. Invoking noty works when I directly use within the template like this:
<form data-dojo-attach-point="formNode" data-dojo-type="dijit/form/Form"
enctype="application/x-www-form-urlencoded" action=${submitUrl} method="post">
<script type="dojo/on" data-dojo-event="submit">
if(!this.validate()){
noty({
text: '${messages.invalidForm}',
type: 'error',
modal: true,
timeout: 2000, // false, to wait for user click
closeWith: ['click', 'hover'], // ['click', 'button', 'hover']
}); // works
return false;
}
return true;
</script>
<!-- other fields -->
</form>
However noty fails to show when created within onSubmit method like this:
<form data-dojo-attach-point="formNode" data-dojo-type="dijit/form/Form"
enctype="application/x-www-form-urlencoded" action=${submitUrl} method="post" data-dojo-attach-event="onSubmit:handleSubmit">
</form>
//Within the template.js
handleSubmit: function() {
if(!this.formNode.validate()) {
noty({text:...}); //fails to come up
return false;
}
return true;
}
dojoConfig:
// ... preceding dojo packages
{ name: "jquery", location: "lib", main: "jquery-1.10.2.min" },
{ name: "noty", location: "lib", main: "jquery.noty.packaged.min" }
It fails to come up in the console too. I guess I've correctly AMD'd the libraries since it works in the first instance. Could anyone please point out any missing links in my implementation. Thanks.
Answering my own question. I got this working by loading noty as a non-amd file:
//Within the template.js
define([..., 'resources/js/lib/jquery.noty.packaged.min.js'], function(...) {
handleSubmit: function() {
if(!this.formNode.validate()) {
noty({text:...}); //fails to come up
return false;
}
return true;
}
})
Sorry for the long title. Its quite hard to put into words.
Ember version: 1.2.0
here goes:
My components:
App.AutocompleteComponent = Ember.Component.extend({
searchResults: function() {
var returnValue
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({options},callback);
function callback(results){
returnValue = results;
}
return returnValue;
}.property('searchText')
My Templates:
{{input type="text" value=searchText placeholder="Search..."}}
<ul >
{{#each itemResults}}
<li>{{this.name}}</li>
{{/each}}
</ul>
When i debug using ember chrome debug tool, i can see the component holding the searchResults values correctly. But it is not being updated accordingly in the template.
Any ideas?
if this way of handling/using computed property is not suggested, can suggest any other ways?
Thank you in advance.
You probably want to debounce this (and I don't know what options is, is it a global var?). And the template is itemResults instead of searchResults. http://emberjs.com/api/classes/Ember.run.html#method_debounce
watchSearchResults: function() {
var self = this;
var service = new google.maps.places.AutocompleteService();
var callback= function(results){
self.set('searchResults', results);
}
service.getPlacePredictions({options},callback);
}.observes('searchText')
Thank you kingpin2k for your response,
I have found other way of dealing with returns that obviously didn't work on callbacks and since computed property which in a way requires 'returns' making it not feasible on this use case.
Instead i have opt to using Observers.
By the way, this code is was meant to be dealing with auto complete.
here is the final code:
WebClient.AutocompleteFromComponent = Ember.Component.extend({
searchTextChanged: Em.observer('searchText',function(){
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: this.get('searchText'),
types: ['(regions)'],
componentRestrictions: {
country: 'my'
}
}, function(predictions, status) {
//Start callback function
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, prediction; prediction = predictions[i]; i++) {
console.log(prediction.description);
mapItem = {};
mapItem.name = prediction.description;
mapItem.type = 'map'
mapItem.reference = prediction.reference;
itemResults.push(mapItem);
}
//console.log(itemResults)
self.set('itemResults', itemResults)
});
})
The template code is still the same.
What is the best approach to use Disqus in a single page application?
I see that the angular js docs has implemented it successfully.
Currently our approach looks like is this in our AngularJS app, but it seems unstable, is hard to test, and loads wrong thread ids (the same thread gets loaded almost everywhere).
'use strict';
angular.module('studentportalenApp.components')
.directive('disqusComponent',['$log', '$rootScope', function($log, $rootScope) {
var _initDisqus = function _initDisqus(attrs)
{
if(window.DISQUS) {
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = attrs.threadId;
this.disqus_container_id = 'disqus_thread';
this.page.url = attrs.permalinkUrl;
}
});
}
else
{
$log.error('window.DISQUS did not exist before directive was loaded.');
}
}
//Destroy DISQUS bindings just before route change, to properly dispose of listeners and frame (postMessage nullpointer exception)
$rootScope.$on('$routeChangeStart', function() {
if(window.DISQUS) {
DISQUS.reset();
}
});
var _linkFn = function link(scope, element, attrs) {
_initDisqus(attrs);
}
return {
replace: true,
template: '<div id="disqus_thread"></div>',
link: _linkFn
};
}]);
I also wanted to include Disqus on my AngularJS-powered blog. I found the existing solutions a bit unwieldy so I wrote my own directive:
.directive('dirDisqus', function($window) {
return {
restrict: 'E',
scope: {
disqus_shortname: '#disqusShortname',
disqus_identifier: '#disqusIdentifier',
disqus_title: '#disqusTitle',
disqus_url: '#disqusUrl',
disqus_category_id: '#disqusCategoryId',
disqus_disable_mobile: '#disqusDisableMobile',
readyToBind: "#"
},
template: '<div id="disqus_thread"></div>comments powered by <span class="logo-disqus">Disqus</span>',
link: function(scope) {
scope.$watch("readyToBind", function(isReady) {
// If the directive has been called without the 'ready-to-bind' attribute, we
// set the default to "true" so that Disqus will be loaded straight away.
if ( !angular.isDefined( isReady ) ) {
isReady = "true";
}
if (scope.$eval(isReady)) {
// put the config variables into separate global vars so that the Disqus script can see them
$window.disqus_shortname = scope.disqus_shortname;
$window.disqus_identifier = scope.disqus_identifier;
$window.disqus_title = scope.disqus_title;
$window.disqus_url = scope.disqus_url;
$window.disqus_category_id = scope.disqus_category_id;
$window.disqus_disable_mobile = scope.disqus_disable_mobile;
// get the remote Disqus script and insert it into the DOM
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + scope.disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
});
}
};
});
Advantages
The main advantage of this approach, I think, is that it keeps things simple. Once you have registered the directive with your app, you don't need to write any JavaScript or set any config values in your JavaScript. All configuration is handled by passing attributes in the directive tag like so:
<dir-disqus disqus-shortname="YOUR_DISQUS_SHORTNAME"
disqus-identifier="{{ article.id }}"
disqus-title="{{ article.title }}"
...>
</dir-disqus>
Also, you don't need to alter your index.html file to include the Disqus .js file - the directive will dynamically load it when it is ready. This means that all that extra .js will only get loaded on those pages that actually use the Disqus directive.
You can see the full source and documentation here on GitHub
Caveat
The above will only work properly when your site is in HTML5Mode, i.e. not using the "#" in your URLs. I am updating the code on GitHub so the directive will work when not using HTML5Mode, but be warned that you must set a hashPrefix of "!" to make "hashbang" URLs - e.g. www.mysite.com/#!/page/123. This is a limitation imposed by Disqus - see http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites
I know nothing about Disqus, but according to the AngularJS Documentation source code:
They bind a load function to afterPartialLoaded:
$scope.afterPartialLoaded = function() {
var currentPageId = $location.path();
$scope.partialTitle = $scope.currentPage.shortName;
$window._gaq.push(['_trackPageview', currentPageId]);
loadDisqus(currentPageId);
};
Then, they simply add the html to the page:
function loadDisqus(currentPageId) {
// http://docs.disqus.com/help/2/
window.disqus_shortname = 'angularjs-next';
window.disqus_identifier = currentPageId;
window.disqus_url = 'http://docs.angularjs.org' + currentPageId;
// http://docs.disqus.com/developers/universal/
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://angularjs.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
angular.element(document.getElementById('disqus_thread')).html('');
}
This is how we solved it.
We load DISQUS in the body of index.html, and resets it whenever there is a directive using it.
Directive:
'use strict';
angular.module('fooApp.directives')
.directive('disqusComponent',['$window', '$log', function($window, $log) {
var _initDisqus = function _initDisqus(scope)
{
if($window.DISQUS) {
$window.DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = scope.threadId;
this.disqus_container_id = 'disqus_thread';
}
});
}
else
{
$log.error('window.DISQUS did not exist before directive was loaded.');
}
}
var _linkFn = function link(scope, element, attrs) {
element.html('<div id="disqus_thread"></div>');
_initDisqus(scope);
}
return {
replace: true,
template: 'false',
scope: {
threadId: '#'
},
link: _linkFn
};
}]);
This is how it can be tested:
'use strict';
describe('Directive: Disqus', function() {
var element, $window, $rootScope, $compile;
beforeEach(function() {
module('fooApp.directives', function($provide) {
$provide.decorator('$window', function($delegate) {
$delegate.DISQUS = {
reset: jasmine.createSpy()
};
return $delegate;
});
});
inject(function(_$rootScope_, _$compile_, _$window_) {
$window = _$window_;
$rootScope = _$rootScope_;
$compile = _$compile_;
});
});
it('should place a div with id disqus_thread in DOM', function() {
element = angular.element('<disqus-component></disqus-component>');
element = $compile(element)($rootScope);
expect(element.html()).toBe('<div id="disqus_thread"></div>');
});
it('should do a call to DISQUS.reset on load', function() {
element = angular.element('<disqus-component thread-id="TESTTHREAD"></disqus-component>');
element = $compile(element)($rootScope);
var resetFn = $window.DISQUS.reset;
expect(resetFn).toHaveBeenCalled();
});
});
I'm trying to implement this (the one at the bottom of the page) RegExp to validate email addresses with jquery validation plugin.
This is my code:
$.validator.addMethod("email_address", function(value, element, param) {
var email_regexp = new RegExp("[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:a-z0-9?.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b", "g");
var result = value.match(email_regexp);
return result ? result.length >= param : false;
}, "Invalid email address");
No JS errors are shown, still it doesn't validate anything! Been playing with it for like an hour and can't get this working!
Is there something wrong?
EDIT: I tried also with // delimiters:
$.validator.addMethod("email_address", function(value, element, param) {
var result = value.match(/[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:a-z0-9?.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b/g);
return result ? result.length >= param : false;
}, "Invalid email address");
~-]+(?:\.[a-z0-9!#$
// ^^
That \. will need escaping again for the Javascript string:
~-]+(?:\\.[a-z0-9!#$
// ^^^
Or, preferably, use // delimeters rather than constructing a RegExp object from a string.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
Why are you writing a custom regex function for the jQuery Validate plugin when it already has an email rule built-in?
http://docs.jquery.com/Plugins/Validation/Methods/email
jQuery:
$(document).ready(function() {
$('#myform').validate({
rules: {
field: {
required: true,
email: true
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field" /> <br/>
<input type="submit" />
</form>
Working Demo:
http://jsfiddle.net/sRwHc/
The default regex function used within the .validate() plugin, FYI:
email: function(value, element) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
}