Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

asp.net - How do I change an .net Core Validator error message using javascript?

I already have an Required field, e.g.:

    [Required(AllowEmptyStrings = false, ErrorMessage = "Fixed error message that I don't want")]
    [BindProperty]
    public string UserName { get; set; }

And properly added all the validation code required, everything is working OK.

However I'm porting an old asp.net framework to .net core, and the system used to set the error messages on the asp:RequiredFieldValidator using javascript with

$("#RequiredFieldValidatorUsername")[0].errormessage = 'some error message';

I couldn't find an easy way to set the errormessage from a Required model field by javascript anywhere (I already have the string on the client side).

Is there a way to accomplish this?

e.g.: The Model class:

public class LoginModel : PageModel
{
public string HeaderScript { get; private set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the name")]
[BindProperty]
public string UserName { get; set; }
}

The view:

<input ID="TextBoxUserName" asp-for="UserName" />
<span asp-validation-for="UserName" class="text-danger"></span>

I already have a Javscript with the string I want to use on the errormessage, I just need to set it instead of the one in the Model.

question from:https://stackoverflow.com/questions/65909504/how-do-i-change-an-net-core-validator-error-message-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This worked, but I'm not sure if it has any drawbacks...

$('#TextBoxUserName').attr('data-val-required', 'my new error message'); 
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('body');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...