【问题标题】:score validation behaves abnormally in Laravel分数验证在 Laravel 中表现异常
【发布时间】:2020-07-13 22:57:56
【问题描述】:

在我的 Laravel-5.8 应用程序中,我有以下代码:

public function findScore(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;
    
    $identities                     = DB::table('identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first()->id;      

   $weightedscore = 0;
   $weightedscore = DB::table('goals')->select(DB::raw("IFNULL(SUM(weighted_score),0) as weighted_score"))->where('identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->whereNull('deleted_at')->first();
   $weightedscorex = 0;

   $maxscore = DB::table('goal_types')->select('max_score')->find($child->parent_id);

    return response()->json([
        'maxscore' => $maxscore->max_score,
        'weightedscore' => $weightedscore->weighted_score,
    ]);        
}

路线:

Route::get('get/findScore','GoalsController@findScore')->name('get.scores.all');

查看(create.blade.php)

          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
              <select id="goal_type" class="form-control @error('goal_type_id') is-invalid @enderror" name="goal_type_id">
              <option value="">Select Goal Type</option>

                @foreach ($categories as $category)
                @unless($category->name === 'Job Fundamentals')
                  <option hidden value="{{ $category->id }}" {{ $category->id == old('goal_type_id') ? 'selected' : '' }}>{{ $category->name }}</option>

                  @if ($category->children)
                    @foreach ($category->children as $child)
                    @unless($child->name === 'Job Fundamentals')
                      <option value="{{ $child->id }}" {{ $child->id == old('goal_type_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option>
                    @endunless
                    @endforeach
                  @endif
                  @endunless
                @endforeach
              </select>

    <input type="hidden" id="max_score" class="form-control" >
    <input type="hidden" id="weighted_score" value="0" class="form-control" >


          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Weight(%):<span style="color:red;">*</span></label> 
              <input  type="text" name="weighted_score" id="total_weighted_score" value="{{ old('weighted_score', $goal->weighted_score) }}" placeholder="Enter weighted score here" class="form-control @error('weighted_score') is-invalid @enderror" max="120" onkeyup="checkScore(this.value)">
            </div>
          </div>  

    <div class="card-footer">
      <button type="submit" class="btn btn-primary">Save</button>
    </div>           

Javascript

    <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#goal_type', function() {
            var air_id =  $(this).val();

            var a = $(this).parent();
            var op = "";
            
            $.ajax({
                type: 'get',
                url: '{{ route('get.scores.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json
                success: function(data) {
                    console.log(data.maxscore);
                    console.log(data.weightedscore);
                     $('#max_score').val(data.maxscore);
                     $('#weighted_score').val(data.weightedscore);
                },
                error:function(){

                }
            });
        });
    });
    </script>
    <script type="text/javascript">
        function checkScore(value){
            let max_score = $("#max_score").val();
            let weighted_score = $("#weighted_score").val();
            let sumValue = parseInt(weighted_score) + parseInt(value);

            if (sumValue > max_score) {
              alert("sum value is greater than max score");
              $("#total_weighted_score").val('');
              return false;
            }
        }
    </script>

在使用 id="goal_type" 更改选择下拉菜单时,我加载了所选目标类型的 max_score。
onkeyup="checkScore(this.value)" 用于验证累计加权分数是否大于 max_score。如果是,那么它会引发警报:

alert("总和值大于最大分数");

这在大多数情况下都非常有效。但是,我发现验证不稳定。有时它不起作用。即使累积的加权分数小于 max_score,它也会发出警报 该问题发生在各种情况下。但有时当用户尝试在文本输入中输入值而不选择下拉菜单时。

我该如何解决这个问题?

【问题讨论】:

  • 你能解释一下“各种场景”吗:)
  • @KurtFriars - 理想情况下,验证应在更改时选择下拉菜单时实施,然后用户键入文本输入。 1.但是如果用户没有选择下拉onchange然后在textinput中输入,就会弹出不应该的警报
  • 以下解决方案对您有用吗?
  • @KurtFriars - 问题已解决。非常感谢
  • 没问题!很高兴为您提供帮助。

标签: javascript laravel


【解决方案1】:

这不一定是最佳解决方案,但应该可以解决您的问题。如果 ajax 尚未返回您的值,但只需以不会触发您的错误的方式对其进行初始化。

function checkScore(value) {
    let max_score = $("#max_score").val();
    max_score = max_score ? parseInt(max_score) : Number.MAX_SAFE_INTEGER;

    let weighted_score = $("#weighted_score").val();
    weighted_score = weighted_score ? parseInt(weighted_score) : 0;
    
    let sumValue = weighted_score + parseInt(value);
    
    if (sumValue > max_score) {
        alert("sum value is greater than max score");
        $("#total_weighted_score").val('');
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 2021-04-02
    • 2015-09-21
    • 2020-01-06
    • 2017-12-10
    • 2015-10-16
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多