Unique Number Input Validation

User
we have
multiple number field make sure each one has different number
Assistant
To ensure that each “ has a unique value across multiple instances, you can implement JavaScript to check and validate the entered numbers dynamically. Here's how you can do it:

### 1. **HTML Setup**
Assume you have multiple input fields rendered dynamically with Laravel:

@foreach ($Competences as $Competence)
    <input 
        type="number" 
        name="position[]" 
        class="form-control position-field" 
        value="{{ $Competence['position'] }}" 
        placeholder="Display order*" 
        required
    >
@endforeach

### 2. **Add JavaScript for Validation**
You can include a script that checks for duplicate values and prevents the user from entering the same number in multiple fields:

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const positionFields = document.querySelectorAll('.position-field');

        positionFields.forEach(field => {
            field.addEventListener('input', () => {
                const values = Array.from(positionFields).map(input => input.value);
                const duplicates = values.filter((val, index, self) => self.indexOf(val) !== index && val !== "");

                positionFields.forEach(input => {
                    if (duplicates.includes(input.value)) {
                        input.setCustomValidity('Each position must be unique.');
                    } else {
                        input.setCustomValidity('');
                    }
                });
            });
        });
    });
</script>

### Explanation:
1. **Retrieve All Input Fields**: The script selects all input fields with the class `position-field`.
2. **On Input Event**: Listens to user input on each field.
3. **Check for Duplicates**: Collects all current values and identifies duplicates.
4. **Set Custom Validity**: If a duplicate is found, the input field's `setCustomValidity` method sets an error message. This ensures the form won't be submitted until the issue is resolved.

### 3. **Styling for Visual Feedback (Optional)**
Add CSS to highlight duplicate fields:

<style>
    .position-field:invalid {
        border: 2px solid red;
    }
</style>

### 4. **Server-Side Validation**
To reinforce this, add server-side validation in Laravel to ensure no duplicate values are submitted:

$request->validate([
    'position.*' => ['required', 'integer', Rule::distinct()]
], [
    'position.*.distinct' => 'Each position must be unique.'
]);

### Outcome:
– Users are notified in real-time if they enter duplicate values.
– The form cannot be submitted until all values are unique.

User
use jquery
Assistant
Here's how you can achieve the same functionality using jQuery to ensure all “ fields have unique values:

### 1. **HTML Setup**

@foreach ($Competences as $Competence)
    <input 
        type="number" 
        name="position[]" 
        class="form-control position-field" 
        value="{{ $Competence['position'] }}" 
        placeholder="Display order*" 
        required
    >
@endforeach

### 2. **jQuery Script**
Add this jQuery script to handle the validation:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        $('.position-field').on('input', function () {
            const values = [];
            let isDuplicate = false;

            // Loop through all position fields
            $('.position-field').each(function () {
                const value = $(this).val();
                if (value !== "") {
                    // Check for duplicates
                    if (values.includes(value)) {
                        isDuplicate = true;
                        $(this).addClass('duplicate');
                    } else {
                        $(this).removeClass('duplicate');
                        values.push(value);
                    }
                }
            });

            // Set feedback for duplicates
            if (isDuplicate) {
                $('.position-field.duplicate').each(function () {
                    $(this).attr('title', 'Duplicate value detected!').addClass('error');
                });
            } else {
                $('.position-field').removeAttr('title').removeClass('error');
            }
        });
    });
</script>

### 3. **CSS for Feedback**
You can style duplicate fields to make them visually distinct:

<style>
    .position-field.error {
        border: 2px solid red;
    }
    .position-field.error:focus {
        outline: none;
        box-shadow: 0 0 5px red;
    }
</style>

### 4. **How It Works**
1. **Attach an `input` Event Listener**: jQuery listens for changes in any `.position-field`.
2. **Track Values**: It loops through all fields, collects their values, and checks for duplicates.
3. **Highlight Duplicates**: If a duplicate is found, it adds a `duplicate` and `error` class to the respective field and sets a `title` attribute with a warning.
4. **Clear Warnings**: When duplicates are resolved, it removes the warnings and styles.

### 5. **Server-Side Validation**
To complement the client-side check, ensure no duplicates are submitted by adding this validation in Laravel:

$request->validate([
    'position.*' => ['required', 'integer', Rule::distinct()]
], [
    'position.*.distinct' => 'Each position must be unique.'
]);

### Final Outcome:
– Duplicate values are visually flagged with a red border and tooltip.
– The form cannot proceed until all values are unique.

Leave a Comment

Your email address will not be published. Required fields are marked *