> For the complete documentation index, see [llms.txt](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/forms-va-validation.md).

# Forms va Validation

#### Mundarija

1. Forms nima va nima uchun kerak?
2. Template-driven Forms

   2.1 Asosiy tushuncha

   2.2 Login Form
3. Validatsiya (Tekshirish)
4. Reactive Forms (Advanced)
5. FormBuilder (Qisqaroq usul)
6. Nazariy savollar
7. Test

***

{% embed url="<https://youtu.be/NbWIyWmogYw>" %}

### 1. Forms nima va nima uchun kerak?

**Form** - bu foydalanuvchidan ma'lumot to'plash uchun ishlatiladi. Masalan:

* Ro'yxatdan o'tish (ism, email, parol)
* Login (username, password)
* Test topshirish
* Ma'lumot qidirish

Angular da **2 xil** form bor:

1. **Template-driven Forms** (soddaroq)
2. **Reactive Forms** (murakkabroq)

***

### 2. Template-driven Forms

#### 2.1 Asosiy tushuncha

Template-driven forms - HTML template da ishlaydigan oddiy formalar.

**Kerakli modul:**

```tsx
// Qaysi komponentda kerak bo'lsa import qilinadi
import { FormsModule } from '@angular/forms';

@Component({
  imports: [
    FormsModule  // ← Bu kerak!
  ],
  ...
})
```

#### 2.2 Oddiy misol: Login forma

**login.component.ts:**

```tsx
import { Component } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  // Forma ma'lumotlari
  username: string = '';
  password: string = '';

  onSubmit() {
    console.log('Username:', this.username);
    console.log('Password:', this.password);

    // Bu yerda login logikasi
    if (this.username === 'admin' && this.password === '123') {
      alert('Muvaffaqiyatli kirdingiz!');
    } else {
      alert('Username yoki parol xato!');
    }
  }
}

```

**login.component.html:**

```html
<div class="login-form">
  <h2>Tizimga kirish</h2>

  <form (ngSubmit)="onSubmit()">
    <!-- Username -->
    <div class="form-group">
      <label>Username:</label>
      <input
        type="text"
        [(ngModel)]="username"
        name="username"
        placeholder="Username kiriting">
    </div>

    <!-- Password -->
    <div class="form-group">
      <label>Parol:</label>
      <input
        type="password"
        [(ngModel)]="password"
        name="password"
        placeholder="Parol kiriting">
    </div>

    <button type="submit">Kirish</button>
  </form>

  <!-- Real-time ko'rsatish -->
  <div class="debug">
    <p>Username: {{ username }}</p>
    <p>Password: {{ password }}</p>
  </div>
</div>

```

**Muhim:**

* `[(ngModel)]` - two-way binding
* `name` atributi **majburiy**
* `(ngSubmit)` - forma submit hodisasi

***

### 3. Validatsiya (Tekshirish)

Foydalanuvchi noto'g'ri ma'lumot kiritsa, xatolikni ko'rsatish kerak.

#### 3.1 Built-in Validators (O'rnatilgan tekshiruvlar)

**Asosiy validatorlar:**

* `required` - majburiy maydon
* `minlength="5"` - minimal uzunlik
* `maxlength="20"` - maksimal uzunlik
* `email` - email formatini tekshirish
* `pattern="regex"` - maxsus format

#### 3.2 Validatsiya bilan misol

**register.component.html:**

```html
<div class="register-form">
  <h2>Ro'yxatdan o'tish</h2>

  <form #registerForm="ngForm" (ngSubmit)="onSubmit()">

    <!-- Ism -->
    <div class="form-group">
      <label>Ism:</label>
      <input
        type="text"
        [(ngModel)]="name"
        name="name"
        #nameField="ngModel"
        required
        minlength="3"
        placeholder="Ismingizni kiriting">

      <!-- Xatolik xabarlari -->
      @if (nameField.invalid && nameField.touched) {
        <div class="error">
          @if (nameField.errors?.['required']) {
            <span>Ism majburiy!</span>
          }
          @if (nameField.errors?.['minlength']) {
            <span>Ism kamida 3 ta harf bo'lishi kerak!</span>
          }
        </div>
      }
    </div>

    <!-- Email -->
    <div class="form-group">
      <label>Email:</label>
      <input
        type="email"
        [(ngModel)]="email"
        name="email"
        #emailField="ngModel"
        required
        email
        placeholder="Email kiriting">

      @if (emailField.invalid && emailField.touched) {
        <div class="error">
          @if (emailField.errors?.['required']) {
            <span>Email majburiy!</span>
          }
          @if (emailField.errors?.['email']) {
            <span>Email formati noto'g'ri!</span>
          }
        </div>
      }
    </div>

    <!-- Parol -->
    <div class="form-group">
      <label>Parol:</label>
      <input
        type="password"
        [(ngModel)]="password"
        name="password"
        #passwordField="ngModel"
        required
        minlength="6"
        placeholder="Parol kiriting">

      @if (passwordField.invalid && passwordField.touched) {
        <div class="error">
          @if (passwordField.errors?.['required']) {
            <span>Parol majburiy!</span>
          }
          @if (passwordField.errors?.['minlength']) {
            <span>Parol kamida 6 ta belgidan iborat bo'lishi kerak!</span>
          }
        </div>
      }
    </div>

    <!-- Submit button -->
    <button
      type="submit"
      [disabled]="registerForm.invalid">
      Ro'yxatdan o'tish
    </button>
  </form>
</div>

```

**register.component.ts:**

```tsx
import { Component } from '@angular/core';

@Component({
  selector: 'app-register',
  imports: [ReactiveFormsModule],
  templateUrl: './register.component.html'
})
export class RegisterComponent {
  name: string = '';
  email: string = '';
  password: string = '';

  onSubmit() {
    console.log('Ma\\'lumotlar:', {
      name: this.name,
      email: this.email,
      password: this.password
    });

    alert('Ro\\'yxatdan o\\'tdingiz!');
  }
}

```

**CSS (register.component.css):**

```css
.register-form {
  max-width: 400px;
  margin: 50px auto;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

input {
  width: 100%;
  padding: 10px;
  border: 2px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
}

input.ng-invalid.ng-touched {
  border-color: red;
}

input.ng-valid.ng-touched {
  border-color: green;
}

.error {
  color: red;
  font-size: 14px;
  margin-top: 5px;
}

button {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background: #5568d3;
}

```

**Muhim tushunchalar:**

* `#nameField="ngModel"` - maydonni o'zgaruvchiga saqlash
* `nameField.invalid` - maydon yarqosizligini bildiradi
* `nameField.touched` - maydonga foydalanuvchi bosganini bildiradi
* `nameField.errors` - xatolar ro’yxati

***

### 4. Reactive Forms (Advanced)

Reactive forms - TypeScript da boshqariladigan formalar. Murakkab formalar uchun yaxshi.

#### 4.1 Kerakli modul

```tsx
// qaysi componentda ishlatilmoqchi bo'lsa import qilinadi
import { ReactiveFormsModule } from '@angular/forms';

@Component({
  imports: [
    ReactiveFormsModule  // ← FormsModule o'rniga
  ],
  ...
})

```

#### 4.2 Oddiy misol

**contact.component.ts:**

```tsx
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-contact',
  imports: [ ReactiveFormsModule ],
  templateUrl: './contact.component.html'
})
export class ContactComponent implements OnInit {
  contactForm!: FormGroup;

  ngOnInit() {
    // Forma yaratish
    this.contactForm = new FormGroup({
      name: new FormControl('', [
        Validators.required,
        Validators.minLength(3)
      ]),
      email: new FormControl('', [
        Validators.required,
        Validators.email
      ]),
      message: new FormControl('', [
        Validators.required,
        Validators.minLength(10)
      ])
    });
  }

  onSubmit() {
    if (this.contactForm.valid) {
      console.log(this.contactForm.value);
      alert('Xabar yuborildi!');
      this.contactForm.reset();
    }
  }

  // Qulaylik uchun getter'lar
  get name() {
    return this.contactForm.get('name');
  }

  get email() {
    return this.contactForm.get('email');
  }

  get message() {
    return this.contactForm.get('message');
  }
}

```

**contact.component.html:**

```html
<div class="contact-form">
  <h2>Biz bilan bog'laning</h2>

  <form [formGroup]="contactForm" (ngSubmit)="onSubmit()">

    <!-- Ism -->
    <div class="form-group">
      <label>Ism:</label>
      <input type="text" formControlName="name">

      @if (name?.invalid && name?.touched) {
        <div class="error">
          @if (name?.errors?.['required']) {
            <span>Ism majburiy</span>
          }
          @if (name?.errors?.['minlength']) {
            <span>Kamida 3 ta harf</span>
          }
        </div>
      }
    </div>

    <!-- Email -->
    <div class="form-group">
      <label>Email:</label>
      <input type="email" formControlName="email">

      @if (email?.invalid && email?.touched) {
        <div class="error">
          @if (email?.errors?.['required']) {
            <span>Email majburiy</span>
          }
          @if (email?.errors?.['email']) {
            <span>Email noto'g'ri</span>
          }
        </div>
      }
    </div>

    <!-- Xabar -->
    <div class="form-group">
      <label>Xabar:</label>
      <textarea formControlName="message" rows="5"></textarea>

      @if (message?.invalid && message?.touched) {
        <div class="error">
          @if (message?.errors?.['required']) {
            <span>Xabar majburiy</span>
          }
          @if (message?.errors?.['minlength']) {
            <span>Kamida 10 ta belgi</span>
          }
        </div>
      }
    </div>

    <button type="submit" [disabled]="contactForm.invalid">
      Yuborish
    </button>
  </form>
</div>

```

#### 4.2 Eng ko’p ishlatiladigan funksionallari

### 1️. FormControl’dan value olish

#### 🔹 `.value`

* **enabled** (faol) control’larning qiymatini qaytaradi
* **disabled** bo‘lsa → qiymat qaytmaydi

```tsx
this.form.get('email')?.value;
```

***

### 2️. FormControl’ga qiymat set qilish

#### 🔹 `setValue()` – hamma control’lar bo‘lishi shart

```tsx
this.form.setValue({
  name: 'Ali',
  email: 'ali@gmail.com'
});
```

#### 🔹 `patchValue()` – faqat keraklisini bersang bo‘ladi ✅

```tsx
this.form.patchValue({
  name: 'Ali'
});
```

***

### 3️. Valid / Invalid tekshirish

#### 🔹 Form darajasida

```tsx
this.form.valid      // true / false
this.form.invalid    // true / false
```

#### 🔹 Control darajasida

```tsx
this.form.get('email')?.valid
this.form.get('email')?.invalid
```

***

### 4️. Validators (tekshiruvchilar)

#### 🔹 Validator qo‘shish

```tsx
this.form = new FormGroup({
  name: new FormControl('', Validators.required),
  email: new FormControl('', [
    Validators.required,
    Validators.email
  ]),
  age: new FormControl(null, Validators.min(18))
});
```

***

### 5️. Error’larni tekshirish

```tsx
const emailCtrl = this.form.get('email');

emailCtrl?.errors
// { required: true }

emailCtrl?.hasError('required') // true
emailCtrl?.hasError('email')    // false
```

***

### 6️. `.value` vs `.getRawValue()` 🔥

#### 🔹 `.value`

* **disabled control’lar YO‘Q**

```tsx
this.form.value
```

#### 🔹 `.getRawValue()`

* **disabled bo‘lsa ham HAMMASI keladi**

```tsx
this.form.getRawValue()
```

#### Example:

```tsx
this.form = new FormGroup({
  name: new FormControl('Ali'),
  role: new FormControl(
    { value: 'admin', disabled: true }
  )
});

this.form.value
// { name: 'Ali' }

this.form.getRawValue()
// { name: 'Ali', role: 'admin' }
```

***

### 5. FormBuilder (Qisqaroq usul)

FormBuilder - formalarni tezroq yaratish uchun.

```tsx
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-student-form',
  templateUrl: './student-form.component.html'
})
export class StudentFormComponent implements OnInit {
  studentForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.studentForm = this.fb.group({
      firstName: ['', [Validators.required, Validators.minLength(2)]],
      lastName: ['', [Validators.required, Validators.minLength(2)]],
      email: ['', [Validators.required, Validators.email]],
      phone: ['', [Validators.required, Validators.pattern(/^\\+998\\d{9}$/)]],
      grade: ['', [Validators.required]]
    });
  }

  onSubmit() {
    if (this.studentForm.valid) {
      console.log(this.studentForm.value);
    }
  }
}

```

**FormBuilder afzalliklari:**

* Qisqa kod
* O'qish oson
* Xatolar kam

***

### Nazorat Savollari

1. **Template-driven va Reactive forms farqi nima?**
2. **ngModel nima uchun kerak?**
3. **Form qanday validatsiya qilinadi?**
4. **`touched` va `dirty` farqi nima?**
5. **FormBuilder nima va nima uchun ishlatiladi?**
6. **ngSubmit nima?**
7. **Formning to’liq qiymatini qanday olish mumkin?**
8. **Formning qiymatini tozalab yuborish uchun nima qilinadi?**
9. **Biror form controldan value qanday olinadi**
10. **Biror form controlga value qanday set qilinadi**

### Test Savollari

**1. Template-driven forms uchun qaysi modul kerak?**

A) BrowserModule

B) FormsModule

C) ReactiveFormsModule

D) HttpClientModule

**2. Two-way binding sintaksisi:**

A) `[ngModel]="name"`

B) `(ngModel)="name"`

C) `[(ngModel)]="name"`

D) `{{ngModel}}="name"`

**3. Form submit hodisasi:**

A) `(submit)="onSubmit()"`

B) `(ngSubmit)="onSubmit()"`

C) `[submit]="onSubmit()"`

D) `{{submit}}="onSubmit()"`

**4. Majburiy maydon uchun:**

A) `required`

B) `mandatory`

C) `needed`

D) `must`

**5. Email validatsiya:**

A) `email`

B) `emailFormat`

C) `validateEmail`

D) `checkEmail`

**6. Minimal uzunlik:**

A) `min="5"`

B) `minlength="5"`

C) `minLength="5"`

D) `minimum="5"`

**7. Maydon yarqsiz degan ma’noni qaysi anglatadi?**

A) `field.error`

B) `field.invalid`

C) `field.wrong`

D) `field.mistake`

**8. Foydalanuvchi maydonga teggan tegmaganini nima anglatadi?**

A) `field.clicked`

B) `field.used`

C) `field.touched`

D) `field.pressed`

**9. Reactive forms uchun qaysi modul talab qilinadi?**

A) `FormsModule`

B) `ReactiveFormsModule`

C) `FormModule`

D) `NgForms`

**10. FormControl qamday yaratiladi?**

A) `new FormControl('')`

B) `FormControl.create()`

C) `createFormControl()`

D) `FormControl.new()`

**11. FormGroup sintaksisi:**

A) `<form [form]="myForm">`

B) `<form [formGroup]="myForm">`

C) `<form (formGroup)="myForm">`

D) `<form {{formGroup}}="myForm">`

**12. FormControl name:**

A) `formName="field"`

B) `formControlName="field"`

C) `controlName="field"`

D) `fieldName="field"`

**13. Form qiymatlari:**

A) `form.value`

B) `form.values`

C) `form.data`

D) `form.fields`

**14. “Form validmi” degani qaysi?**

A) `form.valid`

B) `form.isValid`

C) `form.correct`

D) `form.ok`

**15. Formani tozalash uchun nima qilinadi?**

A) `form.clear()`

B) `form.reset()`

C) `form.empty()`

D) `form.clean()`

**16. FormBuilder orqali FormGroup qanday yaratiladi**

A) `this.fb.group({})`

B) `this.fb.createGroup({})`

C) `this.fb.newGroup({})`

D) `this.fb.makeGroup({})`

> [QuizBot](https://t.me/QuizBot?start=RjGp8Bko)

### Amaliy Topshiriqlar

#### 1. Ro'yxatdan o'tish formasi

**Talablar:**

* Ism (kamida 3 harf, majburiy)
* Familiya (kamida 3 harf, majburiy)
* Email (email format, majburiy)
* Parol (kamida 6 belgi, majburiy)
* Parolni tasdiqlash (parol bilan bir xil bo'lishi kerak)
* Form invalid bo'lganda submit tugmasi disabled bo'lsin

#### 2. Talaba ma'lumotlari formasi

**Talablar:**

* Ism va familiya
* Sinf (1-11 oralig'ida)
* Telefon (+998 format)
* Fan tanlash (checkbox list)
* Izoh (ixtiyoriy, textarea)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://odilbeks-organization.gitbook.io/angular-ustoz-shogirt/forms-va-validation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
