0

I'm trying to use the jQuery validation plugin to validate some text fields on the fly. One of the rules is the field cannot contain 'http'. How would I modify the validate() method to achieve this?

@using (Html.BeginForm("UserDetails", "Account", FormMethod.Post, new {id = "registerform" }))
{
    <input id="Facebook" minlength="2" name="Facebook" placeholder="eg: Joe.Bloggs123" type="text" value>
    ...
}

<script>
    $('#registerform').validate({
        // ...?
    })
</script>

Edit: I tried adding a the validator.addmethod but it still doesn't work. SO here is what I have in the script:

 $('#registerform').validate();

jQuery.validator.addMethod("Facebook", function(value, element) {
            return this.optional(element) || (value.indexOf('http') >= 0);
        }, "*Please just use your userid, not the full url");

Also I would need to validate a lot of these, is it not possible to add a custom class and select from that?

3
  • 1
    u can use customise validation method for this Commented Nov 24, 2016 at 14:25
  • read the documentation: jqueryvalidation.org/jQuery.validator.addMethod and show us what you have tried Commented Nov 24, 2016 at 14:34
  • edited OP with the method I'm trying Commented Nov 24, 2016 at 16:09

2 Answers 2

3

Here is what finally worked for me:

<script>
    jQuery.validator.addMethod("checkhttp", function(value, element) {
                        return this.optional(element) || (value.indexOf('http') < 0) && (value.indexOf('www') < 0);
                    }, "*Please just use your userid, not the full url");

                    jQuery.validator.classRuleSettings.checkhttp = { checkhttp: true };

                $('#registerform').validate();
</script>

@using (Html.BeginForm("UserDetails", "Account", FormMethod.Post, new {id = "registerform" }))
{
     <input id="Facebook" class="checkhttp" name="Facebook" placeholder="eg: Joe.Bloggs123" type="text" value>
}
Sign up to request clarification or add additional context in comments.

Comments

-1

This is for your case but i suggest you use regex

 if( $('#Facebook').val().indexOf('http') >= 0 ) {
  alert('Contains http');
 } else {
  alert('Doesn't contain http');

EDIT I'm sorry, i haven't read the question right.

Add a jQuery validator

jQuery.validator.addMethod("DoesNotContain", function(value, element)
{
    return this.optional(element) || (indexOf('http') < 0);
}, "* Can't contain http");

1 Comment

this is not an jquery.validation implementation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.