Steps to activate ng-pattern exclusively when the field has been interacted with:

I've encountered a challenge with an input box that has an ng-pattern for link validation. Our project manager has requested that the text 'http://' be pre-filled in the input field, but doing so breaks the ng-pattern validation and prevents it from displaying.

<input type="text" ng-model="$parent.emailData.setting.button[2].link" 
 name="button2link" 
 ng-class="{invalid: step3Form.button2link.$invalid}"
 ng-pattern="link_pattern"/>

To provide context, the link pattern is defined as

 $rootScope.link_pattern = /(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/

I'm restating my question to clarify (it's not about styles, which are already functioning) Is there a way to include the actual text 'http://' in the input field without using a placeholder, while still enforcing the link pattern validation?

I want the text 'http://' to automatically appear in the input field when the user sees it (currently just a placeholder) so they don't have to type it themselves.

Answer №1

Here is a possible solution:

Using ng-class="{invalid: (step3Form.button2link.$dirty && step3Form.button2link.$error.pattern)}"

Answer №2

Check out this plunker I put together for you.

http://plnkr.co/edit/GVAdjcjcYczmcmzoCqoF

<form role="form" name="signUpForm" class="form-horizontal">
  <div class="form-group">
      <label for="url" class="col-sm-4 control-label">URL</label>

      <div class="col-sm-8">
          <input type="text" class="form-control" name="url" id="url" placeholder="Enter last name"
                 ng-model="user.lastName" required="true" ng-pattern="/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/">

          <span ng-show="signUpForm.url.$dirty && signUpForm.url.$error.required">
              <small class="text-danger">Please enter a valid URL.</small>
          </span>
          <span ng-show="signUpForm.url.$dirty && signUpForm.url.$error.pattern">
              <small class="text-danger">The URL should contain 2 to 25 characters.</small>
          </span>
      </div>
  </div>
</form>

Answer №3

Check out this code snippet on jsfiddle!

<div ng-app ng-controller="formCtrl">
    <form name="myForm" ng-submit="onSubmit()">
        <input type="number" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required /> <span ng-show="{invalid: (myForm.price_field.$dirty && myForm.price_field.$error.pattern)}">This is not a valid number!</span>
        <input type="submit" value="submit" />
    </form>
</div>

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

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Receive information on browser activity

Is there a way to trigger an event when the following actions occur: Pressing the reload icon in the browser Pressing the Back or Forward icon in the browser Selecting the Reload menu item from the browser context menu Selecting the Reload option from t ...

What is the most effective method for implementing a fallback image in NextJS?

Lately, I've been immersed in a NextJS project that involves utilizing the YoutubeAPI to retrieve video details, such as thumbnail URLs. When it comes to fetching a full resolution image, the thumbnail URL typically follows this format: https://i.yti ...

Utilizing Checkbox to Filter Data in Javascript

Looking for guidance on Javascript as a beginner. I'm attempting to filter and update data based on checkbox selections. The issue lies with Dataset3, where I aim to update the dataset dynamically once checkboxes are selected or deselected. I am stru ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...

Insert the variable into the specified div ID

I am looking to implement an incremental div id system to ensure all my ids are unique. This way, I can make use of jQuery effects to customize them individually. Let me know if you need further clarification on my query. div id ="name_$id" Perhaps I sh ...

The autofocus feature does not function properly in an input tag that is not located within a form element

Is there a way to set the autofocus property in an input element that is not part of a form? I have tried adding the "autofocus" attribute to the input tag but it doesn't seem to be working. <div> //I have added the autofocus property her ...

Retrieving data in Next.js

Exploring various techniques to retrieve information from APIs in next.js. Options include getServerSideProps, getStaticPaths, getStaticProps, Incremental Static Regeneration, and client-side rendering. If I need to send requests to the backend when a s ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

Request for a new login using credentials via ajax

We've set up a web application on a LAMP(PHP) system that makes around 40 Ajax calls. Users are tracked using PHPSessions with a 1 hour cookie lifespan (which we want to maintain for quick expiration). ISSUE: If a user is inactive for the full hour an ...

When trying to call a JavaScript function in PHP Laravel, an error occurs stating that the function

I am currently working on a Laravel project and I have encountered an issue in my blade view with a JavaScript function as shown below: <script type="text/javascript"> function autoFill (dropDown, emptyDropDown) { $("#" + dropDo ...

Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable. For example, if I have AJAX data structured like this: "data": [ { "date" : "1/17/2016", "supplier" : "supplier1", "total" : "$10", "payment" : "Cash", "product" : Array[2] ...

Filtering a string that contains commas using another string that also contains commas

I need help with removing elements from one comma-separated string based on another. String 1: 6,2 String 2: 1,2,4,5,6,7,9,12,13 Is there a function or method that can accomplish this task for me? ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

Pagination determined by the selections made in cascading dropdown menus

Does anyone know of a tutorial on implementing pagination that is specifically tailored to dependent drop lists? I've managed to display associated records based on a selection from a dropdown list with items like {Beavers, Cubs, Scouts, Venturers, Ro ...

What could be causing app.put() to fail in updating documents within mongodb?

I am currently working on implementing a form in an ejs file where, upon clicking a button, the "likes" attribute of a displayed document from my mongoDB collection should be set to 0 using a "PUT" request. However, for some reason, the document does not u ...

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

The token was retrieved as [object Object] in the Ionic framework

Utilizing import { Stripe } from '@ionic-native/stripe' to generate a card token, but encountering the issue where the createCardToken() function is returning an object Object. Upon calling this.stripe.createCardToken(card), the promise should r ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...