验证模型上的输入,返回BadRequest

时间:2018-11-20 13:05:02

标签: angular typescript asp.net-core

对于一个项目,我必须验证用户提供的输入。当用户犯错时,我会在前端显示错误,并提供反馈意见他做了错什么。我像这样验证我的modelState上的输入:

    public class UpdateMatchDayScoreViewModel
{
    public int poolId  { get; set; }
    public int homeTeamId { get; set; }
    public int awayTeamId { get; set; }
    [RegularExpression(@"^\d$", ErrorMessage = "De thuis score kan enkel een getal van 0 tot 10 zijn.")]
    public string scoreHome { get; set; }
    [RegularExpression(@"^\d$", ErrorMessage = "De uit score kan enkel een getal van 0 tot 10 zijn.")]
    public string scoreAway { get; set; }
    public int matchDayId { get; set; }
    public string statusMatchId { get; set; }
    public string homeTeamName { get; set; }
    public string awayTeamName { get; set; }
}

这是我的控制者:

        public async Task<IActionResult> UpdateMatchDayScore([FromBody]UpdateMatchDayScoreViewModel[] model)
    {   
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

我将error中的modelState错误推入错误数组中,如下所示:

errors: string[];
  saveScores() {
if (this.inputSettings.valid) {
  for (var i = 0; i < this.updateScore.length; i++) {
    if (this.updateScore[i]["thuisScore"].value === "" && this.updateScore[i]["uitScore"].value === "") {
      this.updateScore.splice(i, 1);
    } else {
      //find matching game
      let matchData = this.temp.find(game =>
        game.homeTeamName === this.updateScore[i]['thuisPloeg'] &&
        game.awayTeamName === this.updateScore[i]['uitPloeg']);
      // set new scores for game
      if (matchData !== null) {
        console.log(matchData);
        console.log(this.updateScore);
        console.log(this.temp);
        matchData["scoreAway"] = this.updateScore[i]["uitScore"];
        matchData["scoreHome"] = this.updateScore[i]["thuisScore"];
        matchData["statusMatchId"] = this.updateScore[i]["status"];;
      }
      // Delete all unwanted properties from the object
      delete matchData.matchDayDate;
      delete matchData.matchDayTime;
      delete matchData.referee;
      delete matchData.statusMatchCode;
      delete matchData.statusMatchName;
      // Push object in array
      this.updatedMatchScores.push(matchData);
    }
  }
  this.errors = [];
  this.matchDayService.updateMatchDayScore(this.updatedMatchScores).subscribe(
    (data) => { this.successfulSave = true },
    (err) => {
      this.successfulSave = false;
      if (err.status === 400) {
        // handle validation error
        let validationErrorDictionary = err.error;
        for (var fieldName in validationErrorDictionary) {
          if (validationErrorDictionary.hasOwnProperty(fieldName)) {
            this.errors.push(validationErrorDictionary[fieldName]);    
          }
        }
        this.checkModel();
      } else {
        this.errors.push("something went wrong!");
      }
    },
    () => {
      this.startup();  
    });
}

}

我的checkModel方法可以做到这一点:

  checkModel() {
if (this.errors.length > 0) {
  for (let error of this.errors) {
    this.toastr.error(error);
  }
}

if (this.successfulSave) {
  this.toastr.error("Scores zijn succesvol opgeslagen!");
}

}

该启动方法超出了此问题的范围。如何清除modelState错误?我不能只清除错误数组,因为modelState只是将每个错误推回其中,并且每当用户更改输入时,错误就会变成多个。有人可以帮我吗?

0 个答案:

没有答案