About
I am using Angular 13 CLI. There is input type textbox with validation to support only small and upper case characters but due to some reasons, it is allowing to accept other than letter also.
Component - Js
export class ProfileComponent implements OnInit {
public accountForm: any = null;
constructor() {
this.accountForm = new FormGroup({
first_name: new FormControl("", [
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern(/^[a-zA-Z]+$/)
])
});
}
ngOnInit(): void {
}
}
Html
<form [formGroup] = "accountForm">
<input type="text" formControlName="first_name" [value]="this.userData.first_name" />
<span *ngIf="this.accountForm.controls.first_name.errors && this.accountForm.controls.first_name.dirty ">
<ng-container *ngIf="this.accountForm.controls.first_name.errors.required; else second">
This is required
</ng-container>
<ng-template #second>
<ng-container *ngIf="this.accountForm.controls.first_name.errors.minlength; else third">
min length error
</ng-container>
</ng-template>
<ng-template #third>
<ng-container *ngIf="this.accountForm.controls.first_name.errors.maxlength; else fourth">
max length error
</ng-container>
</ng-template>
<ng-template #fourth>
<ng-container *ngIf="this.accountForm.controls.errors.pattern">
Invalid format for first name
</ng-container>
</ng-template>
</span>
<button>Submit</button>
</form>
Late for the answer.
You miss out on specifying the form control (first_name) for displaying the pattern error.
this.accountForm.controls.errors.pattern
It should be:
this.accountForm.controls.first_name.errors.pattern
Related
First to say that I am a newbie in Laravel. I have started to develop the frontend of an APP in Laravel Nova with Livewire. The problem is that before, I was able to do operations in my controller but I don't know how to do it in the Livewire resource.
I have a simple form:
<form wire:submit.prevent="submit" class="rounded px-8 pt-6 pb-8 mb-4">
<input type="text" placeholder="Introduzca código" wire:model="code" class="md:inline-block ktext-gray-700 text-sm font-bold mb-2">
<br>
#error('code')
{{$message}}
#enderror
<br>
<input type="text" placeholder="Introduzca tipo" wire:model="access" class="md:inline-block ktext-gray-700 text-sm font-bold mb-2">
<br>
#error('access')
{{$message}}
#enderror
<br><br>
<x-jet-button type="submit">Crear Asistencia</x-jet-button>
</form>
Which inserts three data into a table:
public function submit()
{
//validate
$this->validate();
Attendance::create([
'code' => $this->code,
'ip' => $_SERVER['REMOTE_ADDR'],
'access' => $this->access,
]);
But I want that in a second table, when the "code" field matches (it is in both tables and is a boolean) the code is update in this second table.
How would you do it? Thanks in advance.
Im not a pro laravel but a think any like the code below can help with yout question:
// If you have more than one register with same code:
$infos = SecondTableModel::where('code', $this->code)->get();
foreach ($infos as $info) {
SecondTableModel::find($info->id)->update([
'ip' => $_SERVER['REMOTE_ADDR'],
'access' => $this->access,
// ... OTHERS FIELSDS
]);
}
// If you have only one register on the second table with the same code
SecondTableModel::where('code', $this->code)->first()->update([
'ip' => $_SERVER['REMOTE_ADDR'],
'access' => $this->access,
// ... OTHERS FIELSDS
]);
I am fetching some data using Apollo inside of Nuxt. Somehow, when navigating to that page I get an error of
Cannot read property 'image' of undefined
When I refresh the page, everything works as expected.
I have a found a few threads of people having similar issues but no solution seems to work for me :/
This is my template file right now:
/products/_slug.vue
<template>
<section class="container">
<div class="top">
<img :src="product.image.url"/>
<h1>{{ product.name }}</h1>
</div>
</section>
</template>
<script>
import gql from 'graphql-tag'
export default {
apollo: {
product: {
query: gql`
query Product($slug: String!) {
product(filter: { slug: { eq: $slug } }) {
slug
name
image {
url
}
}
}
`,
prefetch({ route }) {
return {
slug: route.params.slug
}
},
variables() {
return {
slug: this.$route.params.slug
}
}
}
}
}
</script>
Basically the $apolloData stays empty unless I refresh the page. Any ideas would be much appreciated
EDIT
Got one step closer (I think). Before, everything (image.url and name) would be undefined when navigating to the page for the first time.
I added:
data() {
return {
product: []
};
}
at the top of my export and now at least the name is always defined so if I remove the image, everything works as expected. Just the image.url keeps being undefined.
One thing I noticed (not sure how relevant) is that this issue only occurs using the , if I use a normal a tag it works but of course takes away the vue magic.
EDIT-2
So somehow if I downgrade Nuxt to version 1.0.0 everything works fine
I stumbled on this issue as well, and found it hidden in the Vue Apollo documents.
Although quite similar to the OP's reply, it appears the official way is to use the "$loadingKey" property.
It's quite confusing in the documents because there are so many things going on.
https://vue-apollo.netlify.com/guide/apollo/queries.html#loading-state
<template>
<main
v-if="!loading"
class="my-8 mb-4"
>
<div class="w-3/4 mx-auto mb-16">
<h2 class="mx-auto text-4xl text-center heading-underline">
{{ page.title }}
</h2>
<div
class="content"
v-html="page.content.html"
></div>
</div>
</main>
</template>
<script>
import { page } from "~/graphql/page";
export default {
name: 'AboutPage',
data: () => ({
loading: 0
}),
apollo: {
$loadingKey: 'loading',
page: {
query: page,
variables: {
slug: "about"
}
},
}
}
</script>
If you need to use a reactive property within vue such as a slug, you can do so with the following.
<template>
<main
v-if="!loading"
class="my-8 mb-4"
>
<div class="w-3/4 mx-auto mb-16">
<h2 class="mx-auto text-4xl text-center heading-underline">
{{ page.title }}
</h2>
<div
class="content"
v-html="page.content.html"
></div>
</div>
</main>
</template>
<script>
import { page } from "~/graphql/page";
export default {
name: 'AboutPage',
data: () => ({
loading: 0
}),
apollo: {
$loadingKey: 'loading',
page: {
query: page,
variables() {
return {
slug: this.$route.params.slug
}
}
},
}
}
</script>
I think it's only a problem of timing on page load.
You should either iterate on products, if you have more than one, or have a v-if="product != null" on a product container, that will render only once the data is fetched from GraphQL.
In that way you'll use the object in your HTML only when it's really fetched and avoid reading properties from undefined.
To fix this, you add v-if="!$apollo.loading" to the HTML container in which you're taying to use a reactive prop.
I created a SharePoint Framework Webpart.
I call a webservice that returns some data from sharepoint (terms from termstore), and for each term i generate an html that display the term. On the onclick of each term i want to call a typescript function, passing the term as parameters, to get its children terms.
This code below create the following wrong behaviour: when the webpart is displayed, it automatically calls the function this.readIterm when I didnt even click on it !
Am I missing something or by design doing it the wrong way ? I tried to replace onclick="${this.readIterm(term)}" by onclick="readIterm($(term))" but it does nothing.
Code below
terms.forEach(term => {
htmlContent +=
`<div class="w3-card w3-third w3-margin-bottom" style="" onclick="${this.readIterm(term)}">
<header class="w3-container w3-blue">
<h1>Header</h1>
</header>
<div class="w3-container">
<span>${term.name}</p>
</div>
<footer class="w3-container w3-blue">
<h5>Footer</h5>
</footer>
</div>`
This html is then added to this.domElement.innerHTML, displaying it in the webpart.
public readIterm(myTerm: ITerm) {
alert("readIterm is clicked");
}
Thank you in advance for your help and guidance if I do not follow best practice !
Jeff
There is one more way to attach event listener.
Refer below code sample. This works perfectly for me:
(Note: This is a basic idea. You can refer this code and make changes to yours accordingly.)
public render(): void{
this.domElement.innerHTML = ` <div class="form-group">
<button class="btn btn-success" id="btnReadAllItems">
<span class="ms-Button-label">Read All Items</span>
</button>
<button class="btn btn-success" id="btnReadItemById">
<span class="ms-Button-label">Read Item By Id</span>
</button>
</div>`;
this._setButtonEventHandlers();
}
private _setButtonEventHandlers(): void {
const webPart: SpfxCrudWebPart = this;
this.domElement.querySelector('#btnReadAllItems').addEventListener('click', () => {
this._GetListItemsNF();
});
}
private _GetListItemsNF(): void {
//
//
//
}
Another way is as below. (But you will have to make some changes according to your code)
public render(): void{
htmlContent +=
`<div class="w3-card w3-third w3-margin-bottom" id="test">
<header class="w3-container w3-blue">
<h1>Header</h1>
</header>
<div class="w3-container">
<span>${term.name}</p>
</div>
<footer class="w3-container w3-blue">
<h5>Footer</h5>
</footer>
</div>`
}
this._setButtonEventHandlers();
this.myTerm = term; // Here we are assigning value to the `myTerm` variable. And `myTerm` is a public property, So value of `myTerm` will be accessible using `this.myTerm`
}
public myTerm: ITerm; // here we are declaring `myTerm` variable
public readIterm():void{
// here you can access the cariable `myTerm` using `this.myTerm`.
// alert(this.myTerm);
// alert("readIterm is clicked");
}
private _setButtonEventHandlers(): void {
this.domElement.querySelector('#test').addEventListener('click', () => { this.readIterm(); });
}
Rather onClick instead of onclick. Then check to make sure that you get into your "readIterm" method by calling the console (console.log).
I'm new to Google's Places API. I'm trying to get a Django form to autocomplete, but for some reason, only one of the fields (Street 2) will autocomplete. The rest are just blank. And my console throws no errors, so I really have no idea what the issue is.
The other WEIRD thing . . . the inputs are holding the initial values that I passed to the form from the Django view even though the google autocomplete javascript has set them to "" before trying to autofill them. Is that normal?
Here's the HTML:
<div id="locationField">
<input id="autocomplete" name="search_address" onFocus="geolocate()" placeholder="Search for your address . . ." type="text" />
</div>
<hr class="hr-style">
<div >
<strong>Street</strong>
<input id="street_name" name="street" type="text" value="1030 E State Street" />
</div>
<div >
<strong>Street 2</strong>
<input id="route" name="street2" type="text" value="Apt. 2A" />
</div>
<div >
<strong>City</strong>
<input id="city" name="city" type="text" value="Los Angeles" />
</div>
<div class="6u 12u$(small) ">
<strong>State</strong>
<select id="state" name="state">
<!-- options removed for brevity's sake -->
</div>
<div class="6u 12u$(small) ">
<strong>Zip</strong>
<input id="zipcode" name="zipcode" type="text" value="90210" />
</div>
And the javascript, just copied from Google and modified with my input id's:
//geosearch powered by Google
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
$(function(){
initAutocomplete();
});
var placeSearch, autocomplete;
var componentForm = {
street_name: 'short_name',
route: 'long_name',
city: 'long_name',
state: 'short_name',
zipcode: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation
I'm thinking it has got to be failing somehow at this if statement in fillinAddress(), but I can't tell why:
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
Any help would be appreciated! And here's a screenshot of the form!
Turns out you can NOT rename the address form components. (I had renamed 'locality' to be 'city' and 'administrative_area_level_1' to be 'state.') I'm so new to this; I had no idea! I just thought that the variable names in the javascript had to match your input id's in your HTML. Turns out the address form components have to stay:
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
I want to make mail validation with regex but it's not working.where is my mistake?
It's normally working but when I put a regex control its never see yes the mail you key in is enable for this regex format.
Here is my code;
index.jsp
<head>
<title>Mail Control From Db</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="check.js"></script>
</head>
<body>
<div align="left">
<form name="chkForm" id="chkForm" method="post" >
<table>
<tr>
<td>Email</td>
<td>
<input type="text" name="email" id="email" size="20" ></td>
<td>
<div id="emailInfo" align="left"></div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
check.js
$(document).ready(function()
{
var myForm = $("#chkForm"), email = $("#email"), emailInfo = $("#emailInfo");
//send ajax request to check email
email.blur(function()
{
$.ajax({
type: "POST",
data: "email="+$(this).attr("value"),
url: "check.jsp",
beforeSend: function()
{
emailInfo.html("<font color='blue'>Kontrol Ediliyor..</font>");
},//end beforeSend: function()
success: function(data)
{
var reg = /\S+#\S+\.\S+/;
if (reg.test(email.val()))
{
var checkData = data.toString();
if(checkData == 0)
{
emailok = false;
emailInfo.html("<font color='red'>Mail in use</font>");
}//end if(checkData == 0)
else if(checkData == 1)
{
emailok = true;
emailInfo.html("<font color='green'>Mail is not in use</font>");
}//end else if(checkData == 1)
}//end if (reg.test(email.val()))
else
{
emailInfo.html("<font color='red'>ınvalid mail</font>");
}//end else
}// end success: function(data)
});
});//end email.blur(function()
});//end $(document).ready(function()
I had a problem in check.jsp. and solved it.
problem is about regex.Regex was false.
condition was false. i change it with if (reg.test(email.val())).
Your regex only allows capital letters, so TEXT#EXAMPLE.COM would be okay but test#example.com not. You can change that either by adding the case-insensitive-flag to your regex
/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$/i
or simply allow a-z in the regex itself
/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/
But keep in mind that checking emails for validity is quite a difficult tasks to do, as the range of allowed mail-adresses is extremely broad and they even could contain special-chars like äüö etc. So your regex is not perfect, keep that in mind!
In PHP, I used this function for years and it always seemed to work.
Why exactly are you using .toString() in this case? .test() gives you an boolean which you can perfectly check with == false - is there any reason why you want to convert this to a string?