0

my question is that

I want to make validation in mvc3 in both side ,client as well as server side.

I know how to use validation at server side but i have problem in client side validation.

suppose I have one textbox in view with razor

**Email : @html.Textboxfor(m=>m.Email)**

or

so error will display like this invalide email

now i want to validate email at client side as well as server side.

for client side i want to user my owan javascript file.on submitting form first validate

at client side ,if its validate then and then form will submit and validation at server side will not check. but if user disable script from browser than and than server side validation will get executed,

tereško
  • 58,060
  • 25
  • 98
  • 150
Sagar Hirapara
  • 1,677
  • 13
  • 24
  • actually what you are tyring.. or want to do is bit confusing.. can you elaborate,.... because defining @html.ValidationMessageFor(m=>m.email) will slve your issue... and thats basics of MVC....!! – Pratik Bhatt Feb 01 '13 at 04:35
  • yes that i know but i want to use jquery for validating that like i mean use external .js file – Sagar Hirapara Feb 01 '13 at 04:53

1 Answers1

0

Server side validation should be always enabled and stronger than the client side validation. Some things could be difficult to validate on the client side, like complex interactions between the models or the model properties. However, you can do client validation using the jQuery validator plugin (which comes with the VS MVC project templates). You have your validation attribute on the server, which implements IClientValidatable:

public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{

    public override bool IsValid(object value)
    {
        if (value == null) {
            return true;
        }
        //Add validation rules
        if (false) {
            return false;
        }
        return true;
    }

    public override string FormatErrorMessage(string name)
    {
        return "Please provide valid values."
    }

    public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule {
            ErrorMessage = "Please provide valid values.",
            ValidationType = "validationrule"
        } };
    }
}

On the client side, you will need to add the validation rule:

jQuery.validator.addMethod("validationrule", function (value, element, param) {
    if (value == "") {
        return false;
    }
    return true;
});
jQuery.validator.unobtrusive.adapters.addBool('validationrule');

Make sure you add this outside the jQuery ready handler. See the accepted answer for this question.

Community
  • 1
  • 1
dan radu
  • 2,772
  • 4
  • 18
  • 23