Determine whether a given string is a valid URL and contains content

Is there a way to ensure that one of the input fields is not empty and that the #urlink follows the format of a URL before executing this function in JavaScript?

$scope.favUrls.$add  

I'm uncertain about how to approach this.

html

<input type="text" id="urlName" class="form-control" placeholder=""  ng-model="mvName" />
<input type="text" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" />

app.js

$scope.saveToList = function(event) {

    var mvName = $scope.mvName.trim();
    var mvUrl = $scope.mvUrl.trim();

          if (mvName.length > 0) {
            $scope.favUrls.$add({
              name: mvName,
              title: mvUrl
            });
              urlName.value = ''; //urlName is the ID of  input box - Angular rocks!
            urlLink.value = ''; //urlName is the ID of  input box - Angular rocks!
          }

}

Answer №1

Here is a function that can be used to validate URLs:

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
    '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
    '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
    '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
    '(\?[;&a-z\d%_.~+=-]*)?'+ // query string
    '(\#[-a-z\d_]*)?$','i'); // fragment locater
  if(!pattern.test(str)) {
    alert("Please enter a valid URL.");
    return false;
  } else {
    return true;
  }
}

source

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Reloading the ASP.NET MVC bootstrap modal using Ajax for a fresh look

I'm struggling with my bootstrap modal. Whenever I click the submit button, the page refreshes and the modal disappears. How can I keep the modal open after clicking the submit button to display either a success or error message? I am new to MVC and h ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Detecting the presence of a mobile keyboard on a website: strategies and techniques

After implementing the code below, I noticed that nothing happens when the keyboard is visible. Despite my efforts to troubleshoot, it seems that window.screen.height remains unchanged. class TestPage extends React.Component { constructor(props) { ...

JSP form continues to submit despite JavaScript validation returning false

On my JSP page, I have a form named "deleteCont" and a JavaScript function called "validateDelete". When the user clicks the "Delete contact" button, the "validateDelete" function is triggered successfully, showing an alert message. Unfortunately, even whe ...

What is the best way to ensure a function waits for a stable database connection before proceeding?

Perhaps not phrased well, but I grasp the concepts of async/promises/callbacks. My aim is to develop a module that can be imported (database.js), where I can then execute methods like database.insert() and database.read(). This is the code I have so far: ...

Looking to tilt text at an angle inside a box? CSS can help achieve that effect!

Hey there, is it possible to achieve this with CSS or JavaScript? I require it for a Birt report. ...

Adding up the values of an array of objects by month using ReactJS

To start off, I'm using ChartJS and need to create an array of months. Here's how it looks: const [generatedMonths, setGeneratedMonths] = useState<string[]>([]) const [totalValues, setTotalValues] = useState<number[]>([]) const month ...

Utilize the power of AJAX and Laravel to seamlessly upload an Excel file

I am currently facing an issue with importing an Excel file using AJAX and Laravel in my application. The form of excel import is embedded within another form and I have observed that the error handling is not displaying the error messages correctly on the ...

Rotating an object in Three.js: Animate back and forth along two different azimuth angles

My three.js project features a 3D object that is meant to be viewed from the front only, as it appears as a single plane and is transparent from the back... Using orbitControls, I have restricted movement of both azimuth and polar angle... To enhance the ...

Problem with exporting data from the API to a JavaScript file in Excel format

Instead of receiving actual data in the response, I am getting a set of characters. However, everything works fine when I click on Download file in swagger. Can someone help me diagnose the issue? function downloadDocFile(data: Blob, ext = 'xlsx' ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...

Create and store a new data entry in the custom taxonomy of a specific post

I have successfully added an upload image feature to my custom post type taxonomy. The post type is portfolio, and the taxonomy is portfolio-category. The input field for adding the image (which opens the WordPress uploader) is functioning properly. Howev ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

What is the best approach to conceal elements from the main template in Meteor using a template event?

I have a main template along with two others that are displayed using Iron routing: <template name="main"> <div id="templateMain" name="templateMain"> <a href="nfnoscar">The Legend of NFN Oscar</a> <br/> <a h ...

Add an error message to my throw object within the JSON response

I need to include the error message from the JSON Response of the API in my error object {'status': response.status, 'msg': ''} if there is one, or else just throw the error object without a message. However, currently the thr ...

The path NPM Package is missing in the package export

For my first NPM package, I've been diving into the manuals and exploring other projects for hours to make everything work. Getting Started with the Project https://i.sstatic.net/4JIHz.png The package successfully builds, generating files for ESM an ...

The presence of certain characters is leading to problems in the console

Similar Question: Escaping a String for JavaScript Usage in PHP? The characters in my text are causing errors. When I input special characters such as: !\"$%^&()-=\'.,:;/?#~/\\>< An error saying "Syntax error ...