简体   繁体   中英

Manually add unobtrusive validation to mvc form

This field is optionally validated based on its visibility. If the field is hidden then we don't want to validate it but if it's not hidden then I would want to add required validation.

I'm manually checking it now and stepping through the debugger I can see that the MS unobtrusive validation library is resetting the classes after I've changed the class attribute.

I'm guessing there's some built in methods I can call from the unobtrusive validation library but can't seem to get it figured out.

Model

[Column(TypeName = "varchar")]
[StringLength(150, ErrorMessage = "Url must be less than 151 characters.")]
public string Url { get; set; }

View Javascipt

if ($("#Url").val() === '') {
    $('#Url').addClass('input-validation-error');
    return false;
} else {
    $('#Url').removeClass('input-validation-error');
}

View Form

<div>
    @Html.TextBoxFor(m => m.Url)
    @Html.ValidationMessageFor(m => m.Url)
</div>

Why not just limit input length?

@Html.TextBoxFor(m => m.Url, new { maxlength = 150 })  

Ok, I haven't tried this but I think its roughly what you want

<div>
    @ Html.TextBoxFor(m => m.Url)
    @ If (Model.validateUrl)
      {
         var v = new ValidationMessageFor(m=>m.Url);
         v.GetHtml();
      }
</div>

or it may just be as simple as

<div>
    @ Html.TextBoxFor(m => m.Url)
    @ If (Model.validateUrl)
      {
         @ Html.ValidationMessageFor(m => m.Url)
      }
</div>

I can't quite recall which is the appropriate one, been working so much in angular lately

you cannot add class like that it will not work you have to use $.validator so your code will be like this

      <script type="text/javascript">
$("#Submitbutton")
    .click(function() {


        if ($("#Url").val() === '') {
            $.validator.setDefaults({
                ignore: "#Url"
            });

        } else {
            $.validator.setDefaults({
                ignore: null
            });
            return false;

        }
    });

it will check if its value is null it will ignore the validation else it will display validation error

Ah finally found it!

Here's how to use the built-in validation library to add validation on the fly!

$('#Url').rules('add', {
    required: true
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM